【问题标题】:Search and replace with "whole word only" option [duplicate]搜索并替换为“仅全词”选项[重复]
【发布时间】:2013-07-17 20:03:47
【问题描述】:

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

脚本:

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 多个句子用于搜索和替换工作..

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

【问题讨论】:

  • editor 一个字符串吗?

标签: python


【解决方案1】:

你想要一个正则表达式。您可以使用标记 \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)

【讨论】:

  • 我应该为我当前的脚本替换它吗?在数据库中,我应该在每个单词之前添加 \b ?
  • 例如 \bresult*\bresultado* ?
  • 只需用这个替换你的代码......脚本添加了\bs,所以你不必将它们放在“数据库”中。
  • 所以我替换了您为脚本中的代码编写的代码.. 然后我保存.. 然后我在第三个选项卡中写了“结果”并添加了结果Resultado i> 进入我的数据库.. 然后我运行了脚本.. 但它没有成功
  • @RenanCidale:在要匹配的每个单词之前和之后添加\b,但根本不添加到替换字符串中。确保您使用原始字符串 (r'a raw string'),否则 '\b' 将被解释为退格。
【解决方案2】:

使用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'包围,以确保匹配 仅限整个单词。

  • 使用了替换函数,因此可以替换任何匹配项。

【讨论】:

    【解决方案3】:

    使用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'
    

    【讨论】:

    • 我在哪里替换它
    • 只是让您知道.. 数据库包含超过 1400 个单词.. Result 和 Event 只是示例..
    • 在替换使用中引入一个变量:re.sub(r"\b{}\b".format(variable),"resultado",editor) where variable = "result".
    • 这对我来说很酷
    【解决方案4】:

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

    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)
    

    它会打印出来

    a cat has that thistle.
    

    【讨论】:

      【解决方案5】:
      import re
      
      match = {}  # create a dictionary of words-to-replace and words-to-replace-with
      
      f = open("filename", "r")
      data = f.read()  # string of all file content
      
      
      def replace_all(text, dic):
          for i, j in dic.items():
              text = re.sub(r"\b%s\b" % i, j, text)
              # r"\b%s\b"% enables replacing by whole word matches only
          return text
      
      
      data = replace_all(data, match)
      print(data)  # you can copy and paste the result to whatever file you like
      

      【讨论】:

      • 对我不起作用。它仍然替换部分匹配。请检查
      猜你喜欢
      • 2010-11-05
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 2019-03-28
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多