搜索并替换为"仅限全字"选项

Ren*_*ale 10 python

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

剧本:

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

和数据库示例:

Event*Evento*
result*resultado*
Run Code Online (Sandbox Code Playgroud)

等等...

现在发生的事情是我需要在那个剧本中使用"全字",因为我发现自己遇到了问题.

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

后,我运行脚本的结果保持这样的ResultadoadoEventoo.

只是让你们知道..它不仅仅针对事件和结果,还有超过1000多个句子我已经为搜索设置并替换为工作..

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

kin*_*all 15

你想要一个正则表达式.您可以使用令牌\b来匹配单词边界:即,\bresult\b仅匹配确切的单词"结果".

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)
Run Code Online (Sandbox Code Playgroud)

  • 只需用此代码替换您拥有的代码即可。该脚本添加了\ b,因此您不必将其存储在“数据库”中。 (2认同)

Ste*_*ski 10

用途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.') 
Run Code Online (Sandbox Code Playgroud)

打印

a cat has that thistle.
Run Code Online (Sandbox Code Playgroud)

笔记:

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

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

  • 这些单词被包围r'\b'以确保匹配仅用于整个单词.

  • 使用替换功能以便可以替换任何匹配.


Dhr*_*hak 7

使用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'
Run Code Online (Sandbox Code Playgroud)


小智 5

这很简单。使用 re.sub,不要使用替换。

import re
replacements = {r'\bthe\b':'a', 
                r'\bthis\b':'that'}

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = re.sub(i,j,text)
    return text

replace_all("the cat has this thistle.", replacements)
Run Code Online (Sandbox Code Playgroud)

它会打印

a cat has that thistle.
Run Code Online (Sandbox Code Playgroud)