2014-01-23 89 views
-4

的名單,我想知道哪些主題標籤都採用最在鳴叫,所以我做這樣的排序類型的字典

cursor = db.execute("SELECT text FROM myTable WHERE text LIKE '%#%' ") 
for row in cursor:  
    for word in (re.findall(r"#(\w+)", row[0])): 
     top_hashtags.append(word) 
top_hashtags = {i:top_hashtags.count(i) for i in set(top_hashtags)} 
print sorted(top_hashtags, key=lambda x: x[0]) 

結果是錯誤的。

我用過:print sorted(top_hashtags, key=lambda x: x[0]) 但我認爲它不是像我想要的那樣工作。

+0

這裏沒有任何詞典列表。 –

+0

當你輸入這段代碼時,top_hashtags是什麼類型,你爲什麼將它改寫爲字典? – geoffspear

回答

3

這是這種東西Counter是爲建:

from collections import Counter 
c = Counter(top_hashtags) 
print(c.most_common(5)) # print 5 most common hashtags with counts 

爲了回答您的具體問題,通過價值使用字典鍵排序:

top_ht_dict = {i:top_hashtags.count(i) for i in set(top_hashtags)} 

sorted(top_ht_dict, key=top_ht_dict.get, reverse=True) 
             #^most common first 
+1

您可以使用'top_ht_dict.get'作爲鍵。 –

+0

這很整潔,謝謝 – jonrsharpe

0

你需要的是print sorted(top_hashtags, key=top_hashtags.get, reverse=True)

這將根據hashtag出現的次數對hashtags進行排序,reverse=True使hashtag進入re (即列表中最常見的主題標籤)