疯狂填词----文件读写和正则表达式练习

题目:

创建一个疯狂填词(Mad Libs)程序,它将读入文本文件,并让用户在该文本文件中出现 ADJECTIVE、NOUN、ADVERB 或 VERB 等单词的地方,加上他们自己的文本。结果应该打印到屏幕上,并保存为一个新的文本文件。 

 

代码:

#! python3
# MadLibs.py   -    replace "ADJECTIVE"\"NOUN"\"ADVERB"\"VERB" in a file with the words users enter 
# Usage:
#        python MadLibs.py file.txt    -   Prcesses the file.txt
#        python MadLibs.py     -     pirnts the Usage on the screen

import re,sys,os
replacedWords=["ADJECTIVE","NOUN","ADVERB","VERB"]

#  命令行输入参数为空,print the Usage
if len(sys.argv)==1:
    print('''
    please enter the filename
    # MadLibs.py   -    replace "ADJECTIVE"\"NOUN"\"ADVERB"\"VERB" with the words users enter in a file
    # Usage:
    #        python MadLibs.py file.txt    -   Prcesses the file.txt''')

# 读取文件内容,替换字符串
elif len(sys.argv)==2: 
   #  判断文件是否存在
    if os.path.exists(sys.argv[1])==False:
        print(sys.argv[1]+' does not exist!')
    else:
        with open(str(sys.argv[1]),'r+') as file:
            text=str(file.read())
        # 提醒用户输入待替换的字符串
        for replacedWord in replacedWords:
            newWord=input("Enter an %s:\n"%replacedWord)
            # 写正则表达式,并替换
            Regex=re.compile(replacedWord)
            text=Regex.sub(newWord, text)
            print(text)            
        # T将替换后的字符串写入文件,并关闭文件
        with open('newFile.txt','w') as file:
            file.write(text)

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值