【问题标题】:Unhashable type 'list' - Wordcount不可散列的类型“列表” - 字数
【发布时间】:2015-03-11 17:19:10
【问题描述】:
corpus = PlaintextCorpusReader("path",'.*',encoding="latin1")
docs = [corpus.words(f)for f in corpus.fileids()]
docs2 = [[w.lower()for w in doc]for doc in docs]
docs3 = [[w for w in doc if re.search('^[a-z]+$', w)]for doc in docs2]
from nltk.corpus import stopwords
stop_list = stopwords.words('english')

docs4 = [[w for w in doc if w not in stop_list]for doc in docs3]

我编写了以下代码,它读取文件的语料库。接下来我做了一些预处理步骤,删除了标点符号、停用词等。我现在想进行字数统计并找到文本中最常用的词。我使用下面的代码来做到这一点。 对于 docs4 中的单词:

if word in word_counter:
    word_counter[word] += 1
else:
    word_counter[word] = 1

popular_words = sorted(word_counter, key = word_counter.get, reverse = True)

但是我收到以下错误。 --

Traceback (most recent call last):
  File "C:/Users/rohanhm.2014/PycharmProjects/untitled1/bp.py", line 18, in <module>
    if word in word_counter:
TypeError: unhashable type: 'list'

有什么建议吗?

【问题讨论】:

标签: python regex nltk word-count gensim


【解决方案1】:

我认为“单词”是列表类型。 可能你错误​​地使用了一个列表,里面只包含一个字符串,但你认为它是一个字符串类型。

【讨论】:

    【解决方案2】:

    因为 word_counter 是一个多列表,它是不可散列的。你可以这样写

       from itertools import chain
       print list(chain(*l))
    

    【讨论】:

      【解决方案3】:

      有一种方便的方法可以确定 nltk 中文本的流行词。

      >>> import nltk
      >>> words = ['a','b','a','a','b','c','d']
      >>> fd = nltk.FreqDist(words)
      >>> fd.most_common(3)
      [('a', 3), ('b', 2), ('c', 1)]
      

      【讨论】:

      • 感谢@char 错误。我知道这种方法。但是当 words = [['a','b','b'], ['a','a','c'], ['d','a','d'] 时它不起作用]。这样的列表有什么想法吗?
      • 几个想法! a) word = corpus.words() 将语料库的所有单词存储在一个列表中。 b) words = [w for doc in docs for w in doc] 将您的单词列表合并为一个。 c) fd_list = [nltk.FreqDist(doc) for doc in docs] 获取包含每个文档的 FreqDist 的列表。
      • 用它来查找每个文件的单个字数。 for i in range (len(fids)) : print ("Top Words" + str (i+1) + ":") print (fd_dist[i]) print ("") and wordscount = [w for doc in docs4 for w in doc] 查找总字数。谢谢。
      猜你喜欢
      • 2015-07-05
      • 2017-07-11
      • 2019-08-29
      • 1970-01-01
      • 2023-03-06
      • 2020-03-28
      • 1970-01-01
      • 2014-02-16
      • 2018-12-26
      相关资源
      最近更新 更多