python替换文本文件单词_使用Python中的正则表达式查找并替换文件中的单词列表...

我想将文件的内容打印到终端,并在此过程中突出显示列表中找到的任何单词而不修改原始文件.这是一个尚未运行的代码示例:

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.

如何阻止其他替换丢失?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值