[用Gensim(Python)提取双字母组时发生TypeError

问题描述 投票:0回答:1

我想使用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)

但是有错误:

TypeError

然后我尝试了此:

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)

然后:

again

怎么了?

python machine-learning nlp gensim
1个回答
0
投票
 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]
© www.soinside.com 2019 - 2024. All rights reserved.