【问题标题】:Replacing method for words with boundaries in python (like with regex)用python中的边界替换单词的方法(如使用正则表达式)
【发布时间】:2020-05-15 16:34:40
【问题描述】:

我正在 python 中寻找更强大的替换方法,因为我正在构建一个 拼写检查器在 ocr 上下文中输入单词。

假设我们在 python 中有以下文本:

text =  """
this is a text, generated using optical character recognition. 
this ls having a lot of errors because
the scanned pdf has too bad resolution.
Unfortunately, his text is very difficult to work with. 
"""

很容易意识到,正确的短语应该是“这是一个文本”,而不是“他是一个文本”。 如果我这样做 text.replace('his','this') 然后我会为此替换每个 'his',所以我会得到像“tthis”是文本这样的错误。 当我进行更换时。我想替换整个单词“this”而不是他的或this。 为什么不试试这个?

word_to_replace='his'
corrected_word = 'this'
corrected_text = re.sub('\b'+word_to_replace+'\b',corrected_word,text)
corrected_text 

太棒了,我们做到了,但问题是......如果要更正的单词包含像“|”这样的特殊字符怎么办。例如, '|ights are on' 而不是 'lights are one'。相信我,它发生在我身上,在这种情况下,re.sub 是一场灾难。 问题是,你遇到过同样的问题吗?有什么方法可以解决这个问题吗?换人是最 稳健的选择。 我试过 text.replace(' '+word_to_replace+' ',' '+word_to_replace+' ') 这解决了很多事情,但仍然 有像“his is a text”这样的短语的问题,因为替换在这里不起作用,因为“his”在句子的开头 而不是'他的'为'这个'。

在 python 中是否有任何替换方法可以像 regexs \b word_to_correct \b 那样采用整个单词 作为输入?

【问题讨论】:

  • 我不认为有一个简单的功能可以解决您所说的问题。 OCR 标准化是一个巨大的领域!不过,我确实建议您查看 pypi.org/project/symspellpy,它可以解决 OCR 问题。
  • 非常感谢您的回答,我会去那个图书馆看看。
  • 无需感谢,但如果对您有帮助,请投票支持我的回复。

标签: python regex replace nlp


【解决方案1】:

几天后,我解决了我遇到的问题。我希望这可以 对其他人有所帮助。如果您有任何问题或什么,请告诉我。


text =  """
this is a text, generated using optical character recognition. 
this ls having a lot of errors because
the scanned pdf has too bad resolution.
Unfortunately, his text is very difficult to work with. 
"""


# Asume you already have corrected your word via ocr 
# and you just have to replace it in the text (I did it with my ocr spellchecker)
# So we get the following word2correct and corrected_word (word after spellchecking system)
word2correct = 'his'
corrected_word = 'this'

#
# now we replace the word and the its context
def context_replace(old_word,new_word,text):
    # Match word between boundaries \\b\ using regex. This will capture his and its context but not this  and its context
    phrase2correct = re.findall('.{1,10}'+'\\b'+word2correct+'\\b'+'.{1,10}',text)[0]
    # Once you matched the context, input the new word 
    phrase_corrected = phrase2correct.replace(word2correct,corrected_word)
    # Now replace  the old phrase (phrase2correct) with the new one *phrase_corrected
    text = text.replace(phrase2correct,phrase_corrected)
    return text

测试功能是否有效...

print(context_replace(old_word=word2correct,new_word=corrected_word,text=text))

输出:

this is a text, generated using optical character recognition. 
this ls having a lot of errors because
the scanned pdf has too bad resolution.
Unfortunately, this text is very difficult to work with. 

它符合我的目的。我希望这对其他人有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多