我想将文件的内容打印到终端,并在此过程中突出显示列表中找到的任何单词而不修改原始文件.这是一个尚未运行的代码示例:
def highlight_story(self):
"""Print a line from a file and highlight words in a list."""
the_file = open(self.filename, 'r')
file_contents = the_file.read()
for word in highlight_terms:
regex = re.compile(
r'\b' # Word boundary.
+ word # Each item in the list.
+ r's{0,1}', # One optional 's' at the end.
flags=re.IGNORECASE | re.VERBOSE)
subst = '\033[1;41m' + r'\g<0>' + '\033[0m'
result = re.sub(regex, subst, file_contents)
print result
the_file.close()
highlight_terms = [
'dog',
'hedgehog',
'grue'
]
实际上,只会突出显示列表中的最后一项,无论它是什么或列表有多长.我假设每次替换都会执行,然后在下一次迭代开始时“忘记”.它看起来像这样:
Grues have been known to eat both human and non-human animals. In poorly-lit areas dogs and hedgehogs are considered by any affluent grue to a be delicacies. Dogs can frighten awat a grue, however, by barking in a musical scale. A hedgehog, on the other hand, must simply resign itself to its fate of becoming a hotdog fit for a grue king.
但它应该是这样的:
Grues have been known to eat both human and non-human animals. In poorly-lit areas dogs and hedgehogs are considered by any affluent grue to a be delicacies. Dogs can frighten away a grue, however, by barking in a musical scale. A hedgehog, on the other hand, must simply resign itself to its fate of becoming a hotdog fit for a grue king.
如何阻止其他替换丢失?