搜索并替换为“仅整个单词"选项 [英] Search and replace with "whole word only" option

查看:57
本文介绍了搜索并替换为“仅整个单词"选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a script that runs into my text and search and replace all the sentences I write based in a database.

脚本:

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*

等等...

现在发生的情况是我需要在该脚本中使用仅整个单词",因为我发现自己遇到了问题.

Now what is happening is that I need the "whole word only" in that script, because I'm finding myself with problems.

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

For example with Result and Event, because when I replace for Resultado and Evento, and I run the script one more time in the text the script replace again the Resultado and Evento.

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

And the result after I run the script stays like this Resultadoado and Eventoo.

只是让你们知道..它不仅用于事件和结果,我已经为搜索和替换设置了超过 1000 多个句子.

Just so you guys know.. Its not only for Event and Result, there is more then 1000+ sentences that I already set for the search and replace to work..

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

I don't need a simples search and replace for two words.. because I'm going to be editing the database over and over for different sentences..

推荐答案

您需要正则表达式.您可以使用标记 \b 来匹配单词边界:即,\bresult\b 将仅匹配精确的单词result".

You want a regular expression. You can use the token \b to match a word boundary: i.e., \bresult\b would match only the exact word "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)

这篇关于搜索并替换为“仅整个单词"选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆