我有一个脚本可以运行到我的文本中并搜索并替换我在数据库中编写的所有句子.
剧本:
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)
等等...
现在发生的事情是我需要在那个剧本中使用"全字",因为我发现自己遇到了问题.
例如,使用Result
和Event
,因为当我替换Resultado
和时Evento
,我再次在文本中运行脚本,脚本再次替换Resultado
和Evento
.
后,我运行脚本的结果保持这样的Resultadoado
和Eventoo
.
只是让你们知道..它不仅仅针对事件和结果,还有超过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)
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'
以确保匹配仅用于整个单词.
使用替换功能以便可以替换任何匹配.
使用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)
归档时间: |
|
查看次数: |
22009 次 |
最近记录: |