这是我的代码:
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知识并不奇妙。谢谢!
发布于 2018-07-29 07:27:21
您已经正确地确定了有问题的线路:
file[file.index(word)] = wordRegex.sub(newWord, foundWord.group(), 1)
这一行的问题是,您只替换了foundWord.group()
的一部分,它只包含匹配的单词,而不包含出现在它周围的任何标点符号。
一个简单的解决方法是完全删除foundWord
,只使用word
作为文本进行替换。上面的行将变成:
file[file.index(word)] = wordRegex.sub(newWord, word, 1)
这应该行得通!但是,您可以通过许多其他方式改进您的代码。例如,不需要在file
中搜索word
来获得赋值的正确索引,您应该使用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)
wordRegex.sub
调用中的lambda
等同于以下命名函数:
def func(match):
return input(f'Please Enter A {match.group()}: ')
https://stackoverflow.com/questions/51575504
复制相似问题