首页 > 解决方案 > 使用 Python Madlibs 自动化无聊的东西:替换匹配的正则表达式的麻烦(丢失标点符号)

问题描述

这是我的代码:

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)

当我的程序遇到单词 ADJECTIVE、VERB、ADVERB 和 NOUN 时,它会提示用户输入单词并用输入替换这个占位符。目前,此代码正确替换了单词 HOWEVER,它不保留标点符号。例如这里是 panda.txt:

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

当我用说“吃了”替换动词时,它会这样做,但删除句点:“......然后在附近吃了A......”。

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

标签: pythonregex

解决方案


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

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

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

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

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

那应该工作!但是,您可以通过许多其他方式改进您的代码。例如,不需要搜索fileword获取分配的正确索引,您应该使用enumerate来获取每个的索引word

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)

lambda调用中的wordRegex.sub等价于这个命名函数:

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

推荐阅读