I am counting some specific bigram words frequency. and below are the part of my codes.
sorted_bigrams = sorted(bigrams.items(), key = lambda pair:pair[1], reverse = True)
for bigram, count in sorted_bigrams:
if bigram == ("interesting", "news"):
print count
here, I want to store the counting number of the printing result "count", which is the counting number of bigram "interesting, news"
how can I do it..
If you want to store the total count:
sorted_bigrams = sorted(bigrams.items(), key = lambda pair:pair[1], reverse = True)
total_count = 0
for bigram, count in sorted_bigrams:
if bigram == ("interesting", "news"):
print count
total_count += count
print total_count
If you want to keep track of the breakdown of the counts:
sorted_bigrams = sorted(bigrams.items(), key = lambda pair:pair[1], reverse = True)
counts = []
for bigram, count in sorted_bigrams:
if bigram == ("interesting", "news"):
print count
counts.append(count)
print counts
if bigrams
is a dict storing bigram as key and count as value, then you don't need to sort it in order to get total count as the keys are unique.
if bigrams
is list of tuples, you can use collections.Counter
to get the total count.
In [30]: bigrams
Out[30]: [(('a', 'b'), 10), (('d', 'f'), 3), (('a', 'c'), 15), (('a', 'b'), 2)]
In [31]: counter = Counter()
In [32]: for key, val in bigrams:
counter[key] += val
....:
In [33]: counter[('a', 'b')]
Out[33]: 12
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.