用pythonmadlibs自动化那些无聊的东西:替换匹配的Regex(丢失标点符号)的麻烦

2024-09-28 17:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

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)。在

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

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.

当我用“吃”代替动词时,它会这样做,但去掉句点:“……然后吃附近的……”。在

我相信这个答案不会太复杂,但不幸的是,我的正则表达式知识还不是很好。 谢谢!在


Tags: 代码reifosmaindefgroupword
1条回答
网友
1楼 · 发布于 2024-09-28 17:21:59

您已正确识别出有问题的线路:

file[file.index(word)] = wordRegex.sub(newWord, foundWord.group(), 1)

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

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

^{pr2}$

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

for i, word in enumerate(file):
    if ...
       ...
       file[i] = ...

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

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等效于以下命名函数:

def func(match):
    return input(f'Please Enter A {match.group()}: ')

相关问题 更多 >