gpt4 book ai didi

python - 在 python 中加入单词列表

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:50 25 4
gpt4 key购买 nike

我需要从文本中提取ngrams。我正在使用:

from textblob import TextBlob
text = TextBlob('me king of python')
print(text.ngrams(n=3)

将文本(我的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 循环,因为文本可能有多个 WordList

更新

使用纯 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']]

关于python - 在 python 中加入单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33285194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com