I've been searching in other questions, but I found no help. I got this code:
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)
But when I try to print:
print pairs_freqency()
I get this error:
**Updated
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'
Can someone help me as fast as possible.
Thanks.
TypeError: unhashable type: 'list' Error
happens when you try to use a list
as key in a dict
(or member of set
or frozenset
). The standard way to solve this issue is to cast a list
to tuple
, for example:
In [4]: my_dict = {[2,3,4] : 'a'}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-cda6d34218c4> in <module>()
----> 1 my_dict = {[2,3,4] : 'a'}
TypeError: unhashable type: 'list'
In [5]: my_dict = {tuple([2,3,4]) : 'a'}
In [6]: my_dict
Out[6]: {(2, 3, 4): 'a'}
Counter
needs as its argument an iterable each of whose items is hashable (==can be a key into a dict
). The items in you cases are lists, which are not hashable (because they're mutable). Fix: use tuples instead, specifically in your pairs
method -- instead of
return filter(re.compile(self.pairwise(self.text)).match, list(self.text))
use
return filter(re.compile(self.pairwise(self.text)).match, tuple(self.text))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With