【问题标题】:pyspellchecker: do not split URLpyspellchecker:不要拆分 URL
【发布时间】:2020-03-09 20:20:31
【问题描述】:

我尝试在 Python 中使用 pyspellchecker 设置自动更正。一般来说,它确实有效,但它目前也拆分 URL,这并不是真正需要的。代码如下:

from spellchecker import SpellChecker

spell = SpellChecker()
words = spell.split_words("This is my URL https://test.com")
test = [spell.correction(word) for word in words]

这会导致以下结果: ['this', 'is', 'my', 'URL', 'steps', 'test', 'com']

我要如何更改所有 URL 都不会自动更正?

【问题讨论】:

    标签: python spell-checking autocorrect


    【解决方案1】:

    如果您使用基本 str.split 将句子在每个空格处拆分为单词,它将起作用 (您将失去拆分由除空格以外的任何内容分隔的单词的功能)

    from spellchecker import SpellChecker
    
    spell = SpellChecker()
    words = str.split("This is my URL https://test.com")
    test = [spell.correction(word) for word in words]
    

    输出:

    ['This', 'is', 'my', 'usl', 'https://test.com']

    【讨论】:

      【解决方案2】:

      NLTKTweetTokenizer 正确标记了 URL、主题标签和表情符号。

      >>> from nltk.tokenize import TweetTokenizer
      >>> tknzr = TweetTokenizer()
      >>> tknzr.tokenize(s)
      ['This', 'is', 'my', 'URL', 'https://test.com']
      

      NLTK 带有各种最先进的词标记化原语。我建议您在过滤自动更正之前使用 NLTK 将您的字符串转换为单词。您可以使用 NLTK 的词性实用程序来确定应该自动更正哪些内容。

      【讨论】:

        【解决方案3】:

        您可以定义自己的标记器,然后将其传递给 SpellChecker 类,以便它只会在空格(或您想要的任何其他内容)上分割:

        from spellchecker import SpellChecker
        
        def splitter(words):
            return words.split(" ")    # split on whitespace
        
        spell = SpellChecker(tokenizer=splitter)
        words = spell.split_words("This is my URL https://test.com")
        test = [spell.correction(word) for word in words]
        

        编辑:仅供参考,这样做的原因是因为它看起来像默认标记器使用this regex 将文本拆分为单词。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-06-07
          • 2022-08-03
          • 1970-01-01
          • 2021-07-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多