栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

《Python编程快速上手》--8.9.2 /8.9.3 实践练习

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

《Python编程快速上手》--8.9.2 /8.9.3 实践练习

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()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012206.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号