首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用Python Madlibs自动化无聊的东西:替换匹配的正则表达式的麻烦(丢失标点符号)

用Python Madlibs自动化无聊的东西:替换匹配的正则表达式的麻烦(丢失标点符号)
EN

Stack Overflow用户
提问于 2018-07-29 05:45:30
回答 1查看 517关注 0票数 0

这是我的代码:

代码语言:javascript
复制
import os, re

def madLibs():
    madLibsDirectory = 'madLibsFiles'
    os.chdir(madLibsDirectory)
    madLibsFile = 'panda.txt'
    madLibsFile = open(madLibsFile)
    file = madLibsFile.read()
    madLibsFile.close()

    wordRegex = re.compile(r"ADJECTIVE|VERB|ADVERB|NOUN")
    file = file.split() # split the madlib into a list with each word.
    for word in file:
    # check if word matches regex
        if wordRegex.match(word):
            foundWord = wordRegex.search(word) # create regex object on word
            newWord = input(f'Please Enter A {foundWord.group()}: ') # recieve word
            file[file.index(word)] = wordRegex.sub(newWord, foundWord.group(), 1)  
    file = ' '.join(file)
    print(file)

def main():
    madLibs()

if __name__ == '__main__':
    main()

问题所在的行是file[file.index(word)] = wordRegex.sub(newWord, foundWord.group(), 1)

当我的程序遇到形容词、动词、副词和名词时,它会提示用户输入一个单词,并用输入替换这个占位符。目前这段代码正确地替换了单词,但是它不会保留标点符号。例如,下面是panda.txt:

这个形容词熊猫走到名词,然后是动词。附近的一个名词没有受到这些事件的影响。

当我将动词替换为说" ate“时,它会这样做,但删除句点:"...and then ate A nearby...”。

我确信这个答案并不太复杂,但不幸的是,我的REGEX知识并不奇妙。谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-29 07:27:21

您已经正确地确定了有问题的线路:

代码语言:javascript
复制
file[file.index(word)] = wordRegex.sub(newWord, foundWord.group(), 1)

这一行的问题是,您只替换了foundWord.group()的一部分,它只包含匹配的单词,而不包含出现在它周围的任何标点符号。

一个简单的解决方法是完全删除foundWord,只使用word作为文本进行替换。上面的行将变成:

代码语言:javascript
复制
file[file.index(word)] = wordRegex.sub(newWord, word, 1)

这应该行得通!但是,您可以通过许多其他方式改进您的代码。例如,不需要在file中搜索word来获得赋值的正确索引,您应该使用enumerate来获取每个word的索引:

代码语言:javascript
复制
for i, word in enumerate(file):
    if ...
       ...
       file[i] = ...

或者你可以做一个更大的改变。re.sub函数(和已编译模式对象的等效方法)可以在一次传递中进行多次替换,并且它可以接受一个函数而不是字符串作为替换。每次模式与文本中的模式匹配时,都会使用匹配对象调用该函数。那么,为什么不使用一个函数来提示用户输入替换单词,并一次性替换所有关键字呢?

代码语言:javascript
复制
def madLibs():
    madLibsDirectory = 'madLibsFiles'
    os.chdir(madLibsDirectory)
    filename = 'panda.txt'           # changed this variable name, to avoid duplication
    with open(filename) as file:     # a with statement will automatically close the file
        text = file.read()           # renamed this variable too

    wordRegex = re.compile(r"ADJECTIVE|VERB|ADVERB|NOUN")

    modified_text = wordRegex.sub(lambda match: input(f'Please Enter A {match.group()}: '),
                                  text)     # all the substitutions happen in this one call

    print(modified_text)

wordRegex.sub调用中的lambda等同于以下命名函数:

代码语言:javascript
复制
def func(match):
    return input(f'Please Enter A {match.group()}: ')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51575504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档