在 python 中从给定的字符串生成所有可能的英文单词组合。
输入:godaddy 输出:go, god, dad, add, daddy
有什么好的库吗?
请您参考如下方法:
尝试来自 http://pythonhosted.org/pyenchant/tutorial.html 的 enchant
>>> from nltk import everygrams
>>> import enchant
>>> word = 'godaddy'
>>> [''.join(_ngram) for _ngram in everygrams(word) if d.check(''.join(_ngram))]
['g', 'o', 'd', 'a', 'd', 'd', 'y', 'go', 'ad', 'god', 'dad', 'add', 'daddy']
>>> d = enchant.Dict("en_US")
# Exclude single char words.
>>> [''.join(_ngram) for _ngram in everygrams(word) if d.check(''.join(_ngram)) and len(_ngram) > 1]
['go', 'ad', 'god', 'dad', 'add', 'daddy']
但是如果都是字符串的组合,不管是不是合法的英文单词:
>>> list(everygrams(word))
另见:
- n-grams in python, four, five, six grams?
- Generating Ngrams (Unigrams,Bigrams etc) from a large corpus of .txt files and their Frequency
- extracting n grams from huge text
- Fast/Optimize N-gram implementations in python
- How to compute skipgrams in python?
注意事项
任何字典检查方法都会有其局限性:
>>> from nltk.corpus import words as english
>>> vocab = set(w.lower() for w in english.words())
>>> "google" in vocab
False
>>> "stackoverflow" in vocab
False
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check('StackOverflow')
False
>>> d.check('Stackoverflow')
False
>>> d.check('Google')
True
完成此任务的“原则性”方法是在字符级别进行语言建模,并使用一些概率方法来检查字符序列是否更可能/更不可能作为英语单词。
另外,世界上有很多英国人。英式英语中的“有效”词在美式英语中可能是未知词。参见 http://www.ucl.ac.uk/english-usage/projects/ice.htm和 https://en.wikipedia.org/wiki/World_Englishes#Classification_of_Englishes
