Skip to content

Instantly share code, notes, and snippets.

@kotoripiyopiyo
Created November 27, 2020 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kotoripiyopiyo/9b8c3b3cfe34bd1e3d134d0a13b25864 to your computer and use it in GitHub Desktop.
Save kotoripiyopiyo/9b8c3b3cfe34bd1e3d134d0a13b25864 to your computer and use it in GitHub Desktop.
退屈なことはPythonにやらせよう演習プロジェクト8.10.2
# sample.txtの名刺や形容詞を置き換えて、表示して、sample2.txtに保存
import re
# sample.txtの中身を読み込む
sample_file = open('./sample.txt')
sample_txt = sample_file.read()
# パターンマッチを定義する
word_regex = re.compile(r'ADJECTIVE|NOUN|VERB')
# マッチする限り置換を繰り返す
while True:
mo = word_regex.search(sample_txt)
if mo is None:
break
if mo.group() == 'ADJECTIVE':
repl_word = input('input an ' + mo.group() + '\n')
else:
repl_word = input('input a ' + mo.group() + '\n')
sample_txt = word_regex.sub(repl_word, sample_txt, 1)
# 表示して保存
print(sample_txt)
sample2_file = open('./sample2.txt', 'w')
sample2_file.write(sample_txt)
sample2_file.close()
sample_file.close()
@kotoripiyopiyo
Copy link
Author

sample.txtの中身:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.

The ADJECTIVE NOUN VERB to the NOUN and then VERB.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment