【问题标题】:Python Frequency Distribution (FreqDist / NLTK) IssuePython 频率分布 (FreqDist / NLTK) 问题
【发布时间】:2012-04-19 08:41:45
【问题描述】:

我正在尝试将单词列表(标记化字符串)分解为每个可能的子字符串。然后,我想对每个子字符串运行 FreqDist,以找到最常见的子字符串。第一部分工作正常。但是,当我运行 FreqDist 时,出现错误:

TypeError: unhashable type: 'list'

这是我的代码:

import nltk

string = ['This','is','a','sample']
substrings = []

count1 = 0
count2 = 0

for word in string:
    while count2 <= len(string):
        if count1 != count2:
            temp = string[count1:count2]
            substrings.append(temp)
        count2 += 1
    count1 +=1
    count2 = count1

print substrings

fd = nltk.FreqDist(substrings)

print fd

substrings 的输出很好。这里是:

[['This'], ['This', 'is'], ['This', 'is', 'a'], ['This', 'is', 'a', 'sample'], ['is'], ['is', 'a'], ['is', 'a', 'sample'], ['a'], ['a', 'sample'], ['sample']]

但是,我无法让 FreqDist 在其上运行。任何见解将不胜感激。在这种情况下,每个子字符串的 FreqDist 仅为 1,但该程序旨在运行在更大的文本样本上。

【问题讨论】:

    标签: python nltk frequency-distribution


    【解决方案1】:

    我不完全确定你想要什么,但错误消息是说它想要散列列表,这通常表明它正在将它放在一个集合中或将它用作字典键。我们可以通过给它元组来解决这个问题。

    >>> import nltk
    >>> import itertools
    >>> 
    >>> sentence = ['This','is','a','sample']
    >>> contiguous_subs = [sentence[i:j] for i,j in itertools.combinations(xrange(len(sentence)+1), 2)]
    >>> contiguous_subs
    [['This'], ['This', 'is'], ['This', 'is', 'a'], ['This', 'is', 'a', 'sample'],
     ['is'], ['is', 'a'], ['is', 'a', 'sample'], ['a'], ['a', 'sample'],
     ['sample']]
    

    但我们还有

    >>> fd = nltk.FreqDist(contiguous_subs)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 107, in __init__
        self.update(samples)
      File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 437, in update
        self.inc(sample, count=count)
      File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 122, in inc
        self[sample] = self.get(sample,0) + count
    TypeError: unhashable type: 'list'
    

    如果我们将子序列变成元组,那么:

    >>> contiguous_subs = [tuple(sentence[i:j]) for i,j in itertools.combinations(xrange(len(sentence)+1), 2)]
    >>> contiguous_subs
    [('This',), ('This', 'is'), ('This', 'is', 'a'), ('This', 'is', 'a', 'sample'), ('is',), ('is', 'a'), ('is', 'a', 'sample'), ('a',), ('a', 'sample'), ('sample',)]
    >>> fd = nltk.FreqDist(contiguous_subs)
    >>> print fd
    <FreqDist: ('This',): 1, ('This', 'is'): 1, ('This', 'is', 'a'): 1, ('This', 'is', 'a', 'sample'): 1, ('a',): 1, ('a', 'sample'): 1, ('is',): 1, ('is', 'a'): 1, ('is', 'a', 'sample'): 1, ('sample',): 1>
    

    这就是你要找的吗?

    【讨论】:

      猜你喜欢
      • 2017-11-12
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多