在python中,有没有一种简单的方法从一个无空格的句子中生成一个可能的单词列表?

2024-06-08 00:21:40 发布

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

我有一些短信:

 s="Imageclassificationmethodscan beroughlydividedinto two broad families of approaches:"

我想把它分解成单独的词。我很快地查看了魔法和nltk,但没有看到任何立即有用的东西。如果我有时间在这方面投资的话,我会考虑编写一个动态程序,让enchant能够检查一个单词是否是英语。我本以为网上会有办法的,我错了吗?在


Tags: of程序魔法时间动态短信two我会
2条回答

这是一个在亚洲NLP经常发生的问题。如果你有字典,那么你可以使用这个http://code.google.com/p/mini-segmenter/(免责声明:我写的,希望你不介意)。在

请注意,搜索空间可能非常大,因为英文字母表中的字符数肯定比中文/日语音节长。在

使用trie的贪婪方法

使用Biopythonpip install biopython)尝试此操作:

from Bio import trie
import string


def get_trie(dictfile='/usr/share/dict/american-english'):
    tr = trie.trie()
    with open(dictfile) as f:
        for line in f:
            word = line.rstrip()
            try:
                word = word.encode(encoding='ascii', errors='ignore')
                tr[word] = len(word)
                assert tr.has_key(word), "Missing %s" % word
            except UnicodeDecodeError:
                pass
    return tr


def get_trie_word(tr, s):
    for end in reversed(range(len(s))):
        word = s[:end + 1]
        if tr.has_key(word): 
            return word, s[end + 1: ]
    return None, s

def main(s):
    tr = get_trie()
    while s:
        word, s = get_trie_word(tr, s)
        print word

if __name__ == '__main__':
    s = "Imageclassificationmethodscan beroughlydividedinto two broad families of approaches:"
    s = s.strip(string.punctuation)
    s = s.replace(" ", '')
    s = s.lower()
    main(s)

结果

^{pr2}$

注意事项

在英语中有一些堕落的例子,这是行不通的。您需要使用回溯来处理这些问题,但这应该可以让您开始。在

强制性试验

>>> main("expertsexchange")
experts
exchange

相关问题 更多 >

    热门问题