Python编程快速上手-第8章实践项目答案
2019-01-26 12:49
411 查看
Python编程快速上手-第8章实践参考答案:
在源代码的基础上修改的,源码链接:https://www.geek-share.com/detail/2727072372.html
8.9.2 疯狂填词
import re path = "H:\\Users\\Administrator\\python3.7\\shijian8.9.2" #此文件路径必须存在(也可以自行创建或指定路径) textFile = open(path + "\\tianci.txt") #此文本文件可以不用事先创建,open函数会帮你创建(如果没有的话) text = textFile.read() #把打开的文本对象通过read()方法转换成字符串形式并赋值给变量text。 repWordList = re.compile(r'[A-Z]{2,}').findall(text) #用findall()方法匹配text文本中的正则表达式对象,以列表形式返回。 # repWordList = re.findall(re.compile(r'[A-Z]{2,}'), text) #这里直接用re.findall()函数写,也可以。(我喜欢这种写法) for wordString in repWordList: if wordString[0].lower() == "a" or wordString[0].lower() == "o" or wordString[0].lower() == "i" or \ wordString[0].lower() == "e" or wordString[0].lower() == "u": #元音字母也不是只有一个a啊,还有o,i,e,u。 rep = input('Enter an %s:\n' % wordString.lower()) else: rep = input('Enter a %s:\n' % wordString.lower()) text = text.replace(wordString, rep, 1) #替换,这里第三个参数是可选的,1代表只替换1次。 print(text) new_textFile = open(path + "\\newtianci.txt", "w") new_text = new_textFile.write(text)
8.9.3 正则表达式查找
import re, os #打开.txt path = "H:\\Users\\Administrator\\python3.7\\shijian8.9.2" #此文件路径必须存在(也可以自行创建或指定路径) fileNameList = os.listdir(path) for fileNameString in fileNameList: if fileNameString.endswith(".txt"): txtFileString = open(os.path.join(path, fileNameString)).read() #匹配正则表达式 resultList = re.compile(r'\d{2}').findall(txtFileString) if resultList: print(",".join(resultList) + "----" + fileNameString)
相关文章推荐
- python编程快速上手之第8章实践项目参考答案
- python编程快速上手之第6章实践项目参考答案
- python编程快速上手 第9章实践项目答案
- python编程快速上手之第10章实践项目参考答案
- python编程快速上手之第5章实践项目参考答案
- Python编程快速上手 实践项目8.9.2
- Python编程快速上手 4.10实践项目菜鸟心得
- python编程快速上手之第5章实践项目
- python编程快速上手之第6章实践项目
- Python 编程快速上手 让繁琐工作自动化-第八章实践项目
- Python 编程快速上手 让繁琐工作自动化-第九章实践项目 9.8.1选择性拷贝
- Python编程快速上手 让繁琐工作自动化 | 第三章 :实践项目
- python编程快速上手-第六章实践项目解答
- python编程快速上手 第8章 实践项目 自己写的答案
- python编程快速上手之第9章实践项目参考答案
- python编程快速上手之第3章实践项目参考答案
- Python编程快速上手-第七章实践
- python编程快速上手之第7章实践项目参考答案
- Python编程快速上手-第六章实践
- Python编程快速上手-第四章实践