![](/img/trans.png)
[英]I'm trying to get word frequency on tweet text from a csv file using pandas value counts
[英]How do i split the text part of a tweet to have each word of the text in a new column in a CSV file
將推文輸出到CSV文件,並希望將文本部分分開以使每個單詞都在新列中,因此我可以使用python通過分類器運行它
for tweet in alltweets:
#Loop to only return the tweets that have been posted in the last 24 hours
if (datetime.datetime.now() - tweet.created_at).days < 1:
# transform the tweepy tweets into a 2D array that will populate the csv
outtweets.append([tweet.user.name, tweet.created_at, tweet.text.encode("utf-8")])
else:
deadend = True
return
if not deadend:
page += 1
# write the csv
with open('%s_tweets.csv' % screen_name, 'w') as f:
writer = csv.writer(f)
writer.writerow(["name", "created_at", "text"])
writer.writerows(outtweets)
pass
**編輯2 **
outtweets.append(list(itertools.chain([tweet.user.name, tweet.created_at],tweet.text.encode("utf-8").split(' '))))
TypeError: a bytes-like object is required, not 'str'
由於tweet.text.encode(“ utf-8”)是一個字符串,因此可以在寫入之前將其拆分(按空格)以將其轉換為單個單詞。
tweets = [['user1','text of tweet 1'],['user2','text of tweet2']]
import itertools
for tweet in tweets:
print list(itertools.chain([tweet[0]], tweet[1].split(' ')))
['user1', 'text', 'of', 'tweet', '1']
['user2', 'text', 'of', 'tweet2']
在您的代碼中嘗試代替當前的outtweets.append
outtweets.append(list(itertools.chain([tweet.user.name, tweet.created_at],tweet.text.encode("utf-8").split(' ')))
上面的代碼構建了兩個列表,一個帶有所有舊屬性,一個帶有推文中的單詞,然后將它們合並為一個列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.