Ton*_*oni 5 python error-handling list typeerror python-2.7
我一直在寻找其他问题,但没有找到任何帮助。我得到了这个代码:
def pairs(self, listOrString):
if listOrString:
return filter(re.compile(self.pairwise(self.text)).match, frozenset(self.text))
else:
return ' '.join(filter(re.compile(self.pairwise(self.text)).match, frozenset(self.text)))
def pairs_freqency(self):
return Counter(self.pairs(True))
def sum_pairs(self):
return len(self.ngrams(self.letters(list),2))
def pair_probability(self):
{pair : freqency / self.sum_pairs() for (pair, freqency) in self.pairs_freqency().iteritems()}
def pairwise(self, sequence):
x,y = tee(sequence)
next(y)
return zip(x,y)
Run Code Online (Sandbox Code Playgroud)
但是当我尝试打印时:
print pairs_freqency()
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
**更新
Traceback (most recent call last):
File "...", line 281, in <module>
print pairs(string, text)
File "...", line 46, in get_pairs
return filter(re.compile(self.pairwise(self.text)).match, frozenset(self.text))
File "...", line 190, in compile
return _compile(pattern, flags)
File "...", line 232, in _compile
p = _cache.get(cachekey)
TypeError: unhashable type: 'list'
Run Code Online (Sandbox Code Playgroud)
有人可以尽快帮助我。
谢谢。
Counter需要一个可迭代对象作为其参数,其中每个项目都是可哈希的(==可以是 a 的键dict)。您案例中的项目是列表,它们不可散列(因为它们是可变的)。修复:改用元组,特别是在你的pairs方法中——而不是
return filter(re.compile(self.pairwise(self.text)).match, list(self.text))
Run Code Online (Sandbox Code Playgroud)
使用
return filter(re.compile(self.pairwise(self.text)).match, tuple(self.text))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11795 次 |
| 最近记录: |