8.9.2 疯狂填词
创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本
文件中出现ADJECTIVE、NOUN、ADVERB 或VERB 等单词的地方,加上他们自
己的文本。例如,一个文本文件可能看起来像这样:
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.
程序将找到这些出现的单词,并提示用户取代它们。
Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck
以下的文本文件将被创建:
The silly panda walked to the chandelier and then screamed. A nearby pickup
truck was unaffected by these events.
结果应该打印到屏幕上,并保存为一个新的文本文件。
import re,os
text = input('请输入需要转换的语句:')
regex = re.compile('ADJECTIVE|NOUN|VERB|ADVERB')
while 1:
if regex.search(text):
x = regex.search(text).group().lower()
print('Enter an %s:' % x)
word = input()
text = regex.sub(word,text,count=1)
else:
break
print(text)
path = input('输入文件地址:')
text = text + '\n'
file = open(path,'a')
file.write(text)
file.close()
8.9.3 正则表达式查找
编写一个程序,打开文件夹中所有的.txt 文件,查找匹配用户提供的正则表达
式的所有行。结果应该打印到屏幕上。
folderPath = input('Please input the folderpath : ')
fileNameList = os.listdir(folderPath)
fileNameTXT = []
findNameTXT = re.compile(r'.+\.txt$')
for i in fileNameList:
find = findNameTXT.search(i)
if find != None:
fileNameTXT.append(folderPath + '\\' + find.group()) # 把查找到的 .txt文件变成绝对路径后,放到列表lileNameTXT 中
else:
continue
regex = input('请输入你定义的正则表达式:')
customize = re.compile(regex)
for j in fileNameTXT: # 遍历所有txt文件
# j = os.path.join(folderPath,j)
fileOpen = open(j)
for k in fileOpen:
findRegex = customize.search(k)
if findRegex !=None:
print(findRegex.group())
fileOpen.close()