在 python 中加入 WordLists
Joining WordLists in python
我需要从 text
中提取 ngrams
。我正在使用:
from textblob import TextBlob
text = TextBlob('me king of python')
print(text.ngrams(n=3)
将文本 (me king of python) 拆分为三元组,它给出:
[WordList(['me', 'king', 'of']), WordList(['king', 'of', 'python'])]
现在我需要加入每个 WordList 的项目:
x = {word for word in ' '.join(text.ngrams(n=3)) }
print x
它给了我以下错误:
TypeError: sequence item 0: expected string or Unicode, WordList found
我知道这个解决方案很愚蠢,但我不擅长 python 而且我不明白 wordlists
。
试试这个:
>>> from textblob import TextBlob
>>> blob = TextBlob('me king of python')
>>> trigram = blob.ngrams(n=3)
>>> for wlist in trigram:
... print ' '.join(wlist)
me king of
king of python
更好的是,使用 for 循环,因为文本可以有多个 WordLists
。
更新
使用纯 Python 也可以达到同样的效果。这是一个例子:
>>> def ngrams(s, n=2, i=0):
... while len(s[i:i+n]) == n:
... yield s[i:i+n]
... i += 1
...
>>> grams = ngrams('me king of Python'.split())
>>> list(grams)
[['me', 'king'], ['king', 'of'], ['of', 'Python']]
我需要从 text
中提取 ngrams
。我正在使用:
from textblob import TextBlob
text = TextBlob('me king of python')
print(text.ngrams(n=3)
将文本 (me king of python) 拆分为三元组,它给出:
[WordList(['me', 'king', 'of']), WordList(['king', 'of', 'python'])]
现在我需要加入每个 WordList 的项目:
x = {word for word in ' '.join(text.ngrams(n=3)) }
print x
它给了我以下错误:
TypeError: sequence item 0: expected string or Unicode, WordList found
我知道这个解决方案很愚蠢,但我不擅长 python 而且我不明白 wordlists
。
试试这个:
>>> from textblob import TextBlob
>>> blob = TextBlob('me king of python')
>>> trigram = blob.ngrams(n=3)
>>> for wlist in trigram:
... print ' '.join(wlist)
me king of
king of python
更好的是,使用 for 循环,因为文本可以有多个 WordLists
。
更新
使用纯 Python 也可以达到同样的效果。这是一个例子:
>>> def ngrams(s, n=2, i=0):
... while len(s[i:i+n]) == n:
... yield s[i:i+n]
... i += 1
...
>>> grams = ngrams('me king of Python'.split())
>>> list(grams)
[['me', 'king'], ['king', 'of'], ['of', 'Python']]