pyspellchecker:不要拆分 URL

pyspellchecker: do not split URL

我尝试在 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 都不会自动更正?

您可以定义您自己的分词器并传递给 SpellChecker class,这样它只会按空格(或您想要的任何其他内容)拆分:

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 将文本拆分为单词。

如果您使用基础 str.split 将句子拆分为每个 space 处的单词,它将起作用 (除了 spaces 之外,您将失去拆分单词的功能)

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']

NLTK's TweetTokenizer 正确标记 URL、主题标签和表情符号。

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

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