我想使用TwitterSearch将推文导入到csv中。但是,脚本不会捕获特殊的字符(例如法语中的重音符号)。我已经尝试了几个东西,比如添加.encode('utf-8'),但没有任何成功。使用Python中的TwitterSearch编码错误
如果我尝试写:
tweet_text = tweet['text'].strip().encode('utf-8', 'ignore')
然后我得到
Traceback (most recent call last): File "/Users/usr/Documents/Python/twitter_search2.py", line 56, in <module> get_tweets(query, max_tweets) File "/Users/usr/Documents/Python/twitter_search2.py", line 44, in get_tweets print('@%s: %s' % (user, tweet_text)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 32: ordinal not in range(128)
没有任何人有一个想法?
我在Python 2.7。代码是:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from TwitterSearch import *
import csv
def get_tweets(query, max = 10):
i = 0
search = query
with open(search+'.csv', 'wb') as outf:
writer = csv.writer(outf)
writer.writerow(['user','time','tweet','latitude','longitude'])
try:
tso = TwitterSearchOrder()
tso.set_keywords([search])
tso.set_include_entities(True)
# tso.set_language('fr')
ts = TwitterSearch(
consumer_key = 'YOUR CONSUMER KEY',
consumer_secret = 'YOUR CONSUMER SECRET',
access_token = 'YOUR ACCESS TOKEN',
access_token_secret = 'YOUR ACCESS TOKEN SECRET'
)
for tweet in ts.search_tweets_iterable(tso):
lat = None
long = None
time = tweet['created_at']
user = tweet['user']['screen_name']
tweet_text = tweet['text'].strip().encode('ascii', 'ignore')
tweet_text = ''.join(tweet_text.splitlines())
print i,time,
if tweet['geo'] != None and tweet['geo']['coordinates'][0] != 0.0: # avoiding bad values
lat = tweet['geo']['coordinates'][0]
long = tweet['geo']['coordinates'][1]
print('@%s: %s' % (user, tweet_text)), lat, long
else:
print('@%s: %s' % (user, tweet_text))
writer.writerow([user, time, tweet_text, lat, long])
i += 1
if i > max:
return()
except TwitterSearchException as e:
print(e)
query = raw_input ("Recherche : ")
max_tweets = 10
get_tweets(query, max_tweets)
非常感谢您的帮助!
那么*有什么错误*你得到什么?请包括完整的追溯。 – 2015-03-13 16:11:44
使用此代码,脚本正在工作,但特殊的字符被忽略,不会出现在句子中。我试图找到一种方法来包含它们。 – Flo 2015-03-13 16:16:28
是的,因为您将文本编码为ASCII并忽略所有不适合的内容。这是很多不适合的事情。 – 2015-03-13 16:22:59