【问题标题】:counting words from a file using dictionary doesn't work使用字典计算文件中的单词不起作用
【发布时间】:2014-09-10 16:30:30
【问题描述】:

我正在尝试从推文的 json 文件中计算主题标签。我的程序的目标是首先提取主题标签并制作一个列表,然后创建这些主题标签的字典(为此我编写了“hashtags_dic”函数)以计算每个主题标签出现的次数。我的问题是,现在程序返回主题标签值,但没有总结每个特定主题标签出现的次数。 我创建了一个名为“hashtags_dic”的函数来创建字典,但它不起作用。 代码如下:

from twitter_DB import load_from_DB

def get_entities(tweet):
    if 'entities' in tweet.keys():
        hashtag_list = [hashtag['text'] for hashtag in tweet['entities']['hashtags']]   
        return hashtag_list
    else:
        return []

def hashtags_dic(hashtag_list):       
hashtag_count = {}
for text in hashtag_list:    
    if text != None: 
        if text in hashtag_count.keys():
            hashtag_count[text] = hashtag_count[text] + 1
        else:
            hashtag_count[text] =  1
return hashtag_count

if __name__ == '__main__':
DBname = 'search-results'
tweet_results = load_from_DB(DBname)
print 'number loaded', len(tweet_results) 

for tweet in tweet_results[:100]:
    labels = get_entities(tweet)
    dic=hashtags_dic(labels)
    print '  Hashtags:', labels[:20]
    print ' Hastags count: ', dic

对于我的代码有什么问题的任何提示或想法,我将不胜感激。在此先感谢...诺帕

【问题讨论】:

  • 你能展示一些你的文件是什么样子的输入示例吗?

标签: python twitter dictionary


【解决方案1】:

使用 dict 或 dict 子类(包括 dict.setdefaultcollections.defaultdictcollections.Counter)进行计数的技术有多种。

正如您可能从它的名字中猜到的那样,collections.Counter() 非常适合计数任务 :-)

import collections
import pprint

hash_counts = collections.Counter(hashtags)
print("Fifty most popular hashtags")
pprint.pprint(hash_counts.most_common(50))

FWIW,你原来的 hashtags_dict() 函数似乎工作得很好:

>>> hashtags_dic(['obama', 'putin', 'cameron', 'putin', 'obama'])
{'cameron': 1, 'putin': 2, 'obama': 2}

如果您将text in hashtag_count 替换为text in hashtag_count.keys()hashtags_dict() 函数的工作量会大大减少。前者进行高速散列字典查找,后者使用慢速线性搜索构建键列表。

【讨论】:

    【解决方案2】:

    您可以使用defaultdict 轻松计算唯一主题标签的出现次数。例如:

    from collections import defaultdict
    
    hashtags = ['nice', 'cool', 'great', 'fun', 'nice', 'cool']
    
    hashtag_dict = defaultdict(int)
    
    for k in hashtags:
        hashtag_dict[k] += 1
    
    defaultdict(<type 'int'>, {'fun': 1, 'great': 1, 'cool': 2, 'nice': 2})
    

    【讨论】:

      猜你喜欢
      • 2020-04-21
      • 2017-05-04
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      相关资源
      最近更新 更多