LoginSignup
2
4

More than 5 years have passed since last update.

ムダにクリエイティブな"Hello World"の出力方法一覧(Python3)

Last updated at Posted at 2018-09-12

はじめに

https://qiita.com/KMim/items/dfa1cde772f67ef50618
を拝読させていただき、単純に面白い記事だと思ったのですが、
同時に普段自身の使っている言語の一つであるPythonでどのように再現出来るかと思い、どうせ書くなら公開して他の人の手間を減らそうと思い以下に記します。

即ち、アイデアはパクリに等しいです。
元記事の方から苦情等いただきましたら即時削除です。
僕自身は以下全てのコードの著作権を放棄します。

また、以下出てくるプログラムはPythonの初心者が深夜に1,2時間で書いたものですので、
修正点が多々見つかると思います。
これから見直しつつ逐次修正していきますが、コメント等でなんなりと指摘いただければと思います。

なお、環境は以下の通りです。

% python -V
Python 3.7.0

概要

Pythonの "Hello world" はこちらです。短い。
ちなみに print("Hello World") でも動くので本当はもっと短い。

if __name__ == '__main__':
    print('Hello World')

まずやったこと

上記元記事様のプログラムを噛みしめるように3回復唱し、写経してコンパイルして実行する。

プログラム例

16進数で指定

if __name__ == '__main__':
    print("\u0048"
          "\u0065"
          "\u006c"
          "\u006c"
          "\u006f"
          "\u0020"
          "\u0057"
          "\u006f"
          "\u0072"
          "\u006c"
          "\u0064")

2進数で指定

if __name__ == '__main__':
    # 原作準拠によりとても冗長になっております
    hello_world_letters = ("1001000",
                           "1100101",
                           "1101100",
                           "1101100",
                           "1101111",
                           "100000",
                           "1010111",
                           "1101111",
                           "1110010",
                           "1101100",
                           "1100100")
    hello_world = ""
    for letter in hello_world_letters:
        # 文字列を2進数にする
        bin_letter = int(letter, 2)
        # 2進数を16進数に変換
        hex_letter = hex(bin_letter)
        # (int -> bytes経由で)unicodeに
        x = int(hex_letter, 16)
        hello_world += str(
            int(hex_letter, 16).to_bytes((x.bit_length() + 7) // 8, 'big'),
            'utf-8')
    print(hello_world)

1文字ずつスレッド処理で作成

どっちみちHelloとWorldに分けても1文字づつでも対して変わりゃしないので
バラバラに作ります。
雑に作ったのでJavaのみたいにクラスで作ってありますが、どう見ても関数で定義した方が簡潔なのが目に見えています。原作準拠ということで許して下さい。

import threading


class HelloWorldCallable:

    # 皆さんはちゃんと関数ベースにしましょう
    def __init__(self, num):
        self.message = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
        self._num = num

    def call(self, results: list):
        results.append((self._num, self.message[self._num]))


if __name__ == "__main__":
    # 結果を格納する変数
    hello_list = []
    # threadのリスト
    threads_list = []
    for _ in range(11):
        threads_list.append(
            threading.Thread(target=HelloWorldCallable(_).call(hello_list)))
    try:
        for thread in threads_list:
            thread.start()
        # 終了が確実になるまで待ちます
        for thread in threads_list:
            thread.join()
        # 結果の文字列の生成
        hello_list.sort()
        hello_str = ""
        for x in hello_list:
            hello_str += x[1]
        print(hello_str)
    except Exception as e:
        print(e)

ウェブ上から"Hello World"をスクレイピングして出力

pip などにより beautifulsoup4 及び requests をインストールして下さい。pythonの標準ライブラリでも可能だとは思います。

from bs4 import BeautifulSoup
import requests

if __name__ == '__main__':
    url = "https://ja.wikipedia.org/wiki/Hello_world"
    f = requests.get(url)

    soup = BeautifulSoup(f.content, "html.parser")
    # h1から持ってくる
    value = soup.find("h1").text.title()
    print(value)

ウェブ上から一文字ずつスクレイピングして出力

甘えや妥協を排除しましょう。

from bs4 import BeautifulSoup
import requests


def make_hello_world(urls, locations):
    #  結果を保持する変数
    result = ""
    #  取得する文字列のあるHTML要素(今回はタイトル部分のクラス名)
    target = "firstHeading"
    for index, url in enumerate(urls):
        url = "https://en.wikipedia.org/wiki/" + url
        f = requests.get(url)
        soup = BeautifulSoup(f.content, "html.parser")
        value = soup.find(class_=target).text
        result += value[locations[index]]
    return result


if __name__ == '__main__':
    urls = ["Harry_Potter",
            "The_Human_Centipede_(First_Sequence)",
            "Flying_Spaghetti_Monster",
            "Lil_Wayne",
            "Konjac",
            "Null_pointer",
            "Wikipedia",
            "Morgan_Freeman",
            "Starbucks",
            "Family_Guy",
            "Angry_Birds"]
    # タイトルの何文字目にターゲットの文字があるかを保持
    locations = [0, 2, 1, 2, 1, 4, 0, 1, 3, 4, 9]
    print(make_hello_world(urls, locations))

「こんにちは 世界」をGoogleのAPIで翻訳して出力

(With in progress)

「Hello World」と返すだけのWSGIを仮想サーバに作成する

サーブレットではないのでApache+TomcatではなくWSGIサーバーを立てます。

from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server


def simple_app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]
    start_response(status, headers)
    # このようにリストで書かないと動きません
    return ["Hello World".encode("utf-8"), ] 


if __name__ == '__main__':
    with make_server('', 8080, simple_app) as httpd:
        httpd.serve_forever()

これを拾うスクレイビングのコードです。

import requests

if __name__ == '__main__':
    url = "http://localhost:8080"
    print(requests.get(url).text)

終わりに

Pythonで書くとJavaよりもコーディング量は減る気がします。
ただ、この実装で精神はもっとすり減りました。

2
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4