识别不能在列表项中拼写的字符串

2024-09-26 17:48:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子

['mPXSz0qd6j0 youtube ', 'lBz5XJRLHQM youtube ', 'search OpHQOO-DwlQ ', 
'sachin 47427243 ', 'alex smith ', 'birthday JEaM8Lg9oK4 ', 
'nebula  8x41n9thAU8 ', 'chuck norris  ', 
'searcher O6tUtqPcHDw ', 'graham wXqsg59z7m0 ', 'queries K70QnTfGjoM ']

是否有某种方法可以识别列表项中无法拼写的字符串并将其删除?你知道吗


Tags: searchyoutube单子birthdaysmithnebulaalexchuck
2条回答

例如,可以使用PyEnchant进行基本词典检查,使用NLTK考虑较小的拼写问题,如下所示:

import enchant
import nltk

spell_dict = enchant.Dict('en_US')  # or whatever language supported

def get_distance_limit(w):
    ''' 
    The word is considered good 
    if it's no further from a known word than this limit.
    '''
    return len(w)/5 + 2  # just for example, allowing around 1 typo per 5 chars.

def check_word(word):
    if spell_dict.check(word):
        return True  # a known dictionary word

    # try similar words
    max_dist = get_distance_limit(word)
    for suggestion in spell_dict.suggest(word):
        if nltk.edit_distance(suggestion, word) < max_dist:
            return True

    return False

添加一个案例规范化和数字过滤器,你会得到一个很好的启发式算法。你知道吗

完全可以将列表成员与您认为对您的输入无效的单词进行比较。你知道吗

这可以用很多方法来实现,部分取决于你对“拼写正确”的定义,以及你最终使用什么作为比较列表。如果您认为数字使条目无效,或者下划线或大小写混合,您可以测试正则表达式是否匹配。你知道吗

在regex之后,您必须决定拆分的有效字符应该是什么。是空格吗(你愿意打断‘ad hoc’(‘ad’是缩写,‘hoc’不是单词))?是连字符的吗(这会打断连字符的姓氏)?你知道吗

根据以上标准,我们只需决定使用哪一个单词、专有名称和常用俚语列表以及列表理解:

word_list[:] = [term for term in word_list if passes_my_membership_criteria(term)]

where passes\u my\u membership\u criteria()是一个函数,它包含保留在单词列表中的规则,对于您确定无效的内容返回False。你知道吗

相关问题 更多 >

    热门问题