python - 使用 Gensim(Python)提取二元组时出现 TypeError
问题描述
我想使用 Gensim 提取和打印二元组。为此,我在 GoogleColab 中使用了该代码:
import gensim.downloader as api
from gensim.models import Word2Vec
from gensim.corpora import WikiCorpus, Dictionary
from gensim.models import Phrases
from gensim.models.phrases import Phraser
from collections import Counter
data = api.load("text8") # wikipedia corpus
bigram = Phrases(data, min_count=3, threshold=10)
cntr = Counter()
for key in bigram.vocab.keys():
if len(key.split('_')) > 1:
cntr[key] += bigram.vocab[key]
for key, counts in cntr.most_common(50):
print(key, " - ", counts)
但是有一个错误:
然后我尝试了这个:
cntr = Counter()
for key in bigram.vocab.keys():
if len(key.split(b'_')) > 1:
cntr[key] += bigram.vocab[key]
for key, counts in cntr.most_common(50):
print(key, " - ", counts)
接着:
怎么了?
解决方案
bigram_token = list(bigram.vocab.keys())
type(bigram_token[0])
#op
bytes
将其转换为字符串,它将在您的代码中解决问题,只是在拆分时
cntr = Counter()
for key in bigram.vocab.keys():
if len(key.decode('utf-8').split(b'_')) > 1: # here added .decode('utf-8')
cntr[key] += bigram.vocab[key]
推荐阅读
- html - 有没有办法知道渐变中色标的纯色区域的大小?
- python - 将 for 循环写入列表理解
- cuda - cuda nppiResize() 用于 RGB 图像
- python - Qt Designer 如何为每个文件创建超过 1 个对话框?
- reactjs - 将函数传递给 React 中的子组件 - this.props.handleChange 不是函数?
- ruby - 我可以编写向后兼容 1.8.7 的 ruby 2.3.7 脚本吗?
- amazon-web-services - 无服务器错误:模板格式错误:未解决的资源依赖项 [
LogGroup] 在模板的 Resources 块中 - node.js - 如何使用读取文件制作循环
- java - 如何从数组中打印一系列值?
- python - 使用正则表达式解析多格式字符串