我有一个脚本,它运行到我的文本中,搜索并替换我在数据库中编写的所有句子。
剧本:
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*
等等。。。
现在的情况是我需要剧本中的“全词”,因为我发现自己有问题。
例如使用Result
和Event
,因为当我替换Resultado
和Evento
时,我在文本中再次运行脚本,脚本将再次替换Resultado
和Evento
。
运行脚本后的结果是这样的Resultadoado
和Eventoo
。
只是想让你们知道。。不仅是事件和结果,还有1000多个句子,我已经为搜索和替换工作设置了。。
我不需要简单的搜索和替换两个词。。因为我要为不同的句子一遍又一遍地编辑数据库。。
你想要一个正则表达式。您可以使用标记
\b
来匹配单词边界:即\bresult\b
将只匹配确切的单词“result”使用
re.sub
:印刷品
注意:
所有要替换的字符串都连接成一个模式,因此 字符串只需循环一次。
源字符串被传递给
re.escape
以避免 将它们解释为正则表达式。单词被
r'\b'
包围,以确保匹配是针对 只有整句话。使用替换函数可以替换任何匹配项。
使用
re.sub
而不是普通的字符串替换来替换整个单词。因此,即使脚本再次运行,也不会替换已经替换的单词。相关问题 更多 >
编程相关推荐