Created
November 27, 2020 12:41
-
-
Save kotoripiyopiyo/9b8c3b3cfe34bd1e3d134d0a13b25864 to your computer and use it in GitHub Desktop.
退屈なことはPythonにやらせよう演習プロジェクト8.10.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.