python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python疯狂填词程序

Python编程快速上手——疯狂填词程序实现方法分析

作者:授我以驴

这篇文章主要介绍了Python疯狂填词程序实现方法,结合具体案例形式分析了Python填词算法相关的文件读写、正则匹配、数据遍历等操作技巧,需要的朋友可以参考下

本文实例讲述了Python疯狂填词程序实现方法。分享给大家供大家参考,具体如下:

题目如下:



Enter an adjective:
silly
Enter a noun:
chandelier
Enter a verb:
screamed
Enter a noun:
pickup truck

思路如下:


代码如下:

import re
def madLibs(longStr):
  madLibsRex = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB') #正则表达式对象
  print(madLibsRex.findall(longStr)) #验证是否模式匹配正确
  return madLibsRex.findall(longStr)

openFile = open('123.txt','r')
longStr = openFile.read() #将文本内容读入变量longStr
print("源文本如下:",longStr)
for i in madLibs(longStr): #循环遍历函数返回的匹配对象列表
  print("Enter an {0}:".format(i))
  longStr = longStr.replace(i,input()) #调用字符串的replace()方法输入替换,再赋值给longStr
print(longStr)
resultFile = open('new123.txt','w') #在当前工作目录创建一个新的文件
resultFile.write(longStr) #将字符串变量写入resultFile对象
openFile.close()
resultFile.close()

结果如下:

在这里插入图片描述

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python列表(list)操作技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:
阅读全文