代码之家  ›  专栏  ›  技术社区  ›  David Anderson

Python拼写检查功能-替换独立单词,但不替换子字符串

  •  0
  • David Anderson  · 技术社区  · 4 年前

    我收集了数千行数据,为经常拼写错误的特定术语创建了拼写检查功能,在写入文件之前自动更正它们。

    如果是像“apple”这样的独立单词,我会用“orange”替换它,但如果是“菠萝”并变成“pineorange”,这就成了一个问题。作为一种变通方法,我在原始术语的两边都加了一个空格,但这会导致它漏掉后面有句号之类的字符的情况,“apple”例如

    我有什么办法来改善这里的操控性?如果不是最后一个角色,最好是其他角色。

    spelling_dict = {
        "abc" : "ABC",
        "apple" : "Apple",
        "tortose" : "Tortoise"
    }
    
    def spellcheck(line):
        for word, correction in spelling_dict.items():
            
            # Pad words with a space on either side
            word = word.center( len(word) + 2 )
            correction = correction.center ( len(correction) + 2 )
    
            line = line.replace(word, correction)
            
        return line
    
    myphrase = "For apple, I want to capitalize both occurrences of apple."
    fixedphrase = spellcheck(myphrase)
    
    print(fixedphrase)
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Paul M.    4 年前

    看起来你想要正则表达式。在本例中,模式(要查找的对象)是字符串 apple 被单词边界包围 \\b :

    import re
    
    pattern = "\\bapple\\b"
    
    phrase = "apple pineapple apples and apple."
    
    print(re.sub(pattern, "orange", phrase))
    

    输出:

    orange pineapple apples and orange.
    >>> 
    

    注意 苹果 apple. 被替换为 orange orange. 但是 pineapple apples 保持不变。