【发布时间】:2017-09-11 02:17:39
【问题描述】:
我正在从 twitter 收集一堆推文并将它们保存到列表中,然后将列表转换为 numpy 数组并尝试将其保存到 CSV 文件中。
但是,当我尝试这样做时,出现以下错误:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1215, in savetxt
fh.write(asbytes(format % tuple(row) + newline))
TypeError: a float is required
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/keva161/Documents/Projects/Twitter Sentiment/main.py", line 66, in <module>
main("Trump")
File "/home/keva161/Documents/Projects/Twitter Sentiment/main.py", line 20, in main
collect_tweets(api, query)
File "/home/keva161/Documents/Projects/Twitter Sentiment/main.py", line 54, in collect_tweets
save_to_csv(tweets_array)
File "/home/keva161/Documents/Projects/Twitter Sentiment/main.py", line 62, in save_to_csv
np.savetxt('test.csv', tweets_array)
File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1219, in savetxt
% (str(X.dtype), format))
TypeError: Mismatch between array dtype ('<U144') and format specifier ('%.18e %.18e %.18e %.18e %.18e %.18e %.18e')
下面是我的代码:
def collect_tweets(api, query):
tweets_array = []
public_tweets = api.search(q=query, count=10)
print("Collecting tweets...")
for tweet in public_tweets:
userid = api.get_user(tweet.user.id)
username = userid.screen_name
location = tweet.user.location
tweetText = tweet.text
analysis = TextBlob(tweet.text)
polarity = analysis.sentiment.polarity
datestamp = tweet.created_at
time = datestamp.strftime("%H:%M")
year = datestamp.strftime("%d-%m-%Y")
if (not tweet.retweeted) and ('RT @' not in tweet.text):
retweet = "Yes"
else:
retweet = "No"
tweets_array.append([username, location, tweetText, retweet, time, year, polarity])
print("Done!")
save_to_csv(tweets_array)
def save_to_csv(tweets_array):
print('Saving to CSV')
new_array = np.array(tweets_array)
#headers = ['Username', 'Location', 'Tweet', 'Retweeted', 'Time', 'Year', 'Polarity']
#np.savetxt("test_file.csv", new_array.flatten(), delimiter=",", fmt='%s')
np.savetxt('test.csv', tweets_array)
【问题讨论】:
-
为什么要将字符串列表转换为 numpy 数组,只是为了保存 csv?这没有任何意义。使用
csv模块 -
但是,是的,您的错误似乎是您传递了一个格式说明符“%.18e”,这意味着科学记数法,当您的数据是文本时,
numpy不知道该怎么做. -
%.18e是默认格式。 -
@hpaulj 对,似乎有一个注释掉的对
savetext的调用指定了%s,但同样,如果这就是你想要的为什么不使用csv模块我>
标签: python arrays csv numpy tweepy