我有一個類 Tweet 包含幾條推文。然后是一個包含所有推文的串列。這些推文也有用戶、轉發數量和年齡,這與我的問題無關。只有內容很重要。
tweet1 = Tweet("@realDonaldTrump", "盡管有負面新聞 covfefe #bigsmart", 1249, 54303)
tweet2 = Tweet("@elonmusk", "從技術上講,酒精是一種解決方案#bigsmart", 366.4, 166500)
tweet3 = Tweet("@CIA", "我們既不能確認也不能否認這是我們的第一條推文。#heart", 2192, 284200)
推文 = [tweet1,tweet2,tweet3]
我需要獲取所有主題標簽的串列,但我只從第一條推文中獲取帶有我的代碼的標簽。
for x in tweets:
return re.findall(r'#\w ', x.content)
uj5u.com熱心網友回復:
您將在回圈的第一次迭代后回傳。您需要瀏覽所有推文并將標簽添加到串列中:
def get_hashtags(tweets):
result = []
for x in tweets:
result.extend(re.findall(r'#\w ', x.content))
return result
對于排序,您可以使用 defaultdict 來添加轉推。然后,按數量排序。
from collections import defaultdict
def get_hashtags_sorted(tweets):
result = defaultdict(int)
for x in tweets:
for hashtag in re.findall(r'#\w ', x.content):
result[hashtag] = x.retweets
sorted_hashtags = sorted(tweets.items(), key=lambda x: x[1])
return list(sorted_hashtags)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527755.html
標籤:Python列表哎呀推特
