这是我的代码:
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.
当我用“吃”代替动词时,它会这样做,但去掉句点:“……然后吃附近的……”。在
我相信这个答案不会太复杂,但不幸的是,我的正则表达式知识还不是很好。 谢谢!在
您已正确识别出有问题的线路:
这一行的问题是您只替换了
foundWord.group()
的一部分,它只包含匹配的单词,而不是它周围出现的任何标点符号。在一个简单的修复方法是完全删除
^{pr2}$foundWord
,只需使用word
作为文本来进行替换。上面的行将变成:那应该行得通!但是,您可以通过许多其他方法改进代码。例如,您不需要在}的索引:
file
中搜索word
以获得分配的正确索引,而应该使用enumerate
来获取每个{或者你可以做更大的改变。
re.sub
函数(以及编译的模式对象的等效方法)可以在一个过程中进行多次替换,并且它可以使用一个函数而不是字符串作为替换。每次模式在文本中匹配时,都将使用匹配对象调用函数。那么为什么不使用一个函数来提示用户输入替换词,并一次性替换所有的关键字呢?在调用
wordRegex.sub
中的lambda
等效于以下命名函数:相关问题 更多 >
编程相关推荐