zoukankan      html  css  js  c++  java
  • Python-正则与文件项目(疯狂填词)

    创建一个疯狂填词(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.

    源码:

     1 # coding=utf-8
     2 import re
     3 # 打开文件
     4 wfile = open('sentence.txt','r')
     5 words = wfile.read()
     6 wfile.close()
     7 print(words)
     8 #正则读取单词并依次替换单词
     9 wRegex = re.compile(r'w[A-Z]+')
    10 for content in wRegex.findall(words):
    11     replaceContent= input('Enter a %s:
    '%content)
    12     #print(content)
    13     #print(replaceContent)
    14     regex = re.compile(content)   #将匹配出的单词作为正则查找规则,再词查找并用输入的内容替换
    15     words=regex.sub(replaceContent,words,1)  # 替换的内容继续保存在原来文件读取的内容中,不然替换的内容不会被保存,sub函数添加数量是因为有两个NOUN,会把同时替换,所以设置一次只替换一个
    16 print(words)
    17 #新内容写入新文件
    18 nwfile= open('sentence1.txt','w')
    19 nwfile.write(words)
    20 nwfile.close()
  • 相关阅读:
    钉钉 LDAP
    OpenLDAP 密码策略与审计控制
    Active Directory LDAP DingDing
    Linux kill 命令 java
    Memory Analyzer 与 Java VM 版本支持问题
    java.lang.Thread.State
    稻盛和夫 活法 人生公式
    [领导力/管理]一句话说带团队
    把某个公司git项目迁移到gitee的步骤
    Protocol Buffers  |  Google Developers
  • 原文地址:https://www.cnblogs.com/Annaying/p/9142318.html
Copyright © 2011-2022 走看看