1
1

More than 3 years have passed since last update.

【Python】正規表現を利用していつ・どこで・だれが・何をしたゲーム

Last updated at Posted at 2020-04-30

目的

・正規表現を学んだのでとりあえず楽しく使ってみる

環境

  • Visual Studio Code
  • Python

手順

すべてひとつのファイル(practice.py)に書きました。

①正規表現のための標準ライブラリであるreモジュールをインポート

practice.py
import re

②質問を用意

practice.py
question = "いつ?どこで?だれが?何をした?"

③関数four_ws_gameを定義

practice.py
def four_ws_game(sentence):
    words = re.findall(".*??", sentence)
    i = 0
    while i < len(words):
        answer = input(f"{words[i]}:").strip()
        if answer == "":
            print("真面目にやってください")
        else:
            sentence = sentence.replace(words[i], answer)
            i += 1
    print(sentence)

わかりづらいので分解して見てみましょう。

3-1. reモジュールのfindall関数を利用

  • findall関数は文章(sentence)の中で一致した部分をリストにして変数wordsに渡します
    • 正規表現における. (ピリオド)は任意の一文字を意味する
    • * (アスタリスク)は繰り返しを意味する
practice.py
words = re.findall(".*??", sentence)

つまりこのプログラムは、文章(sentense)の中から末尾に?(全角クエスチョン)が付く任意の文字数の単語探し出し、リスト化します。

  • ?(半角クエスチョン)は上記の単語を一つ一つ分けて取り出すために必要です
    • ?(半角クエスチョン)の有無でリストの中身がどう変わるのか見てみましょう
practice.py
words = re.findall(".*??", sentence)
print(words)
実行結果
['いつ?', 'どこで?', 'だれが?', '何をした?']
practice.py
words = re.findall(".*?", sentence)
print(words)
実行結果
['いつ?どこで?だれが?何をした?']

3-2. 文章(sentence)の中身を入力値に書き換えてプリント

practice.py
i = 0
while i < len(words):
    answer = input(f"{words[i]}:").strip()
    if answer == "":
        print("真面目にやってください")
    else:
        sentence = sentence.replace(words[i], answer)
        i += 1
print(sentence)

④sentenceを最初に用意した質問(question)にして実行

practice.py
four_ws_game(question)

コード全体

practice.py
import re

question = "いつ?どこで?だれが?何をした?"

def four_ws_game(sentence):
    words = re.findall(".*??", sentence)
    i = 0
    while i < len(words):
        answer = input(f"{words[i]}:").strip()
        if answer == "":
            print("真面目にやってください")
        else:
            sentence = sentence.replace(words[i], answer)
            i += 1
    print("何があったの?:" + sentence)

four_ws_game(question)
  • 実行結果
いつ?:きのう
どこで?:家で
だれが?:ねこが
何をした?:ねころんだ
何があったの?:きのう家でねこがねころんだ
  • 空欄にしようとすると怒られます
いつ?:きのう
どこで?:
真面目にやってください
どこで?:家で
だれが?:ねこが
何をした?:
真面目にやってください
何をした?:犬になった
何があったの?:きのう家でねこが犬になった
1
1
0

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
1
1