python - 使用 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 知识还不是很好。谢谢!
解决方案
您已正确识别出有问题的线路:
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)
lambda
调用中的wordRegex.sub
等价于这个命名函数:
def func(match):
return input(f'Please Enter A {match.group()}: ')
推荐阅读
- javascript - 无法在移动设备上使用 Nivo 工具提示或十字准线可拖动性
- smartsheet-api - 内容改变时调用 Web Service
- flutter - 如何在颤动中动态更改堆栈中项目的位置?
- mysql - 删除范围内的十亿条记录与精确 ID 查找 MYSQL
- spring-boot - 使用状态存储的多实例 kafka 流
- c# - Magick.Net 问题压缩 PDF 文件的位图
- yaml - Yaml - 如何在单行中编写映射
- database - 在文件中连续存储时间序列数据向量的最佳方法是什么?
- javascript - 数据在 .map() 中可用,但在 .subscribe() 中不可用 - 角度 5
- android-studio - 未调用 Android Studio OnFling 事件