[英]how can i store the printing result, obtained by “for statement” variable?
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" 在这里,我要存储打印结果“ count”的计数,这是二元组“有趣,新闻”的计数
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. 如果
bigrams
是一个将bigram作为键存储并作为值计数的字典,则由于键是唯一的,因此无需对其进行排序即可获得总计数。
if bigrams
is list of tuples, you can use collections.Counter
to get the total count. 如果
bigrams
是元组列表,则可以使用collections.Counter
获取总计数。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.