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

我有一些文字:

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

我想把它解析成单词.我很快就看到了附魔和nltk,但没有看到任何看起来很有用的东西.如果我有时间投资这个,我会研究一下写一个动态程序,附魔能够检查一个单词是否是英文.我会以为网上有什么事要做,我错了吗?

最佳答案
使用特技的贪婪的方式

尝试使用Biopython(点安装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)

结果

>>> if __name__ == '__main__':
...     s = "Imageclassificationmethodscan beroughlydividedinto two broad families of approaches:"
...     s = s.strip(string.punctuation)
...     s = s.replace(" ", '')
...     s = s.lower()
...     main(s)
... 
image
classification
methods
can
be
roughly
divided
into
two
broad
families
of
approaches

注意事项

英文中有堕落的情况,这不会奏效.你需要使用回溯来处理这些,但这应该让你开始.

强制性测试

>>> main("expertsexchange")
experts
exchange

转载注明原文:有没有一个简单的方法可以从python中的空格句子生成一个可能的单词列表? - 代码日志