搜索并替换为“仅全词”选项

2024-09-29 00:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它运行到我的文本中,搜索并替换我在数据库中编写的所有句子。

剧本:

with open('C:/Users/User/Desktop/Portuguesetranslator.txt') as f:
    for l in f:
        s = l.split('*')
        editor.replace(s[0],s[1])

数据库示例:

Event*Evento*
result*resultado*

等等。。。

现在的情况是我需要剧本中的“全词”,因为我发现自己有问题。

例如使用ResultEvent,因为当我替换ResultadoEvento时,我在文本中再次运行脚本,脚本将再次替换ResultadoEvento

运行脚本后的结果是这样的ResultadoadoEventoo

只是想让你们知道。。不仅是事件和结果,还有1000多个句子,我已经为搜索和替换工作设置了。。

我不需要简单的搜索和替换两个词。。因为我要为不同的句子一遍又一遍地编辑数据库。。


Tags: 文本txt脚本event数据库withopenusers
3条回答

你想要一个正则表达式。您可以使用标记\b来匹配单词边界:即\bresult\b将只匹配确切的单词“result”

import re

with open('C:/Users/User/Desktop/Portuguesetranslator.txt') as f:
    for l in f:
        s = l.split('*')
        editor = re.sub(r"\b%s\b" % s[0] , s[1], editor)

使用re.sub

replacements = {'the':'a', 
                'this':'that'}

def replace(match):
    return replacements[match.group(0)]

# notice that the 'this' in 'thistle' is not matched 
print re.sub('|'.join(r'\b%s\b' % re.escape(s) for s in replacements), 
        replace, 'the cat has this thistle.') 

印刷品

a cat has that thistle.

注意:

  • 所有要替换的字符串都连接成一个模式,因此 字符串只需循环一次。

  • 源字符串被传递给re.escape以避免 将它们解释为正则表达式。

  • 单词被r'\b'包围,以确保匹配是针对 只有整句话。

  • 使用替换函数可以替换任何匹配项。

使用re.sub而不是普通的字符串替换来替换整个单词。因此,即使脚本再次运行,也不会替换已经替换的单词。

>>> import re
>>> editor = "This is result of the match"
>>> new_editor = re.sub(r"\bresult\b","resultado",editor)
>>> new_editor
'This is resultado of the match'
>>> newest_editor = re.sub(r"\bresult\b","resultado",new_editor)
>>> newest_editor
'This is resultado of the match'

相关问题 更多 >