第八章 实践项目 疯狂填词
给到文本> The ADJECTIVE walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.
网上看了很多种算法,其中使用将正则表达式放入列表中进行遍历的较多,但是这种方法有个缺点。因为给到的文本中有两个NOUN,利用正则表达式列表进行遍历后,要么就连个NOUN都修改成同一个,要么就未能修改第二个NOUN。
采用我这种方法,可以对所有给到的指定单词逐一修改,知道给到文本查找完成。
#!python
#疯狂填词.py
import re
txtAddress = r'E:\pythonProject\add\8_9_test.txt'
saveAddress = r'E:\pythonProject\add\8_9_save.txt'
txtObj = open(txtAddress)
txtFile = txtObj.read()
txtRegex = re.compile(r'ADJECTIVE|NOUN|VERB|ADVERB')
while txtRegex.search(txtFile):#通过正则表达式查找,每次只找一个,直到找不到为止
wordSub = input('Enter a %s:\n'%txtRegex.search(txtFile).group().lower())
txtFile = txtRegex.sub(wordSub,txtFile,1)#每次只修改匹配到的第一个单词
saveObj = open(saveAddress,'w')
saveObj.write(txtFile)
txtObj.close()
saveObj.close()
修改后文本内容> The silly walked to tye chandelier and then screamed. A nearby pickup truck was unaffected by these events.