2015-03-13 38 views
0

我想使用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) 

非常感谢您的帮助!

+1

那么*有什么错误*你得到什么?请包括完整的追溯。 – 2015-03-13 16:11:44

+0

使用此代码,脚本正在工作,但特殊的字符被忽略,不会出现在句子中。我试图找到一种方法来包含它们。 – Flo 2015-03-13 16:16:28

+0

是的,因为您将文本编码为ASCII并忽略所有不适合的内容。这是很多不适合的事情。 – 2015-03-13 16:22:59

回答

0

你一起用户名插值编码的鸣叫:

print('@%s: %s' % (user, tweet_text)) 

如果user对象是Unicode字符串这会失败:

>>> user = u'Héllo' 
>>> tweet_text = u'Héllo'.encode('utf8') 
>>> '@%s: %s' % (user, tweet_text) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128) 

,因为你是混合类型。 Python尝试解码的值tweet_text再次使其成为unicode对象。

坚持一种类型;要么编码所有内容,要么保留Unicode的所有内容,并在最后一次编码。

你必须编码您user值CSV文件,无论如何,离开鸣叫的编码,直到然后:

tweet_text = tweet['text'].strip() 
tweet_text = u''.join(tweet_text.splitlines()) 
print i, time, 
if tweet['geo'] and tweet['geo']['coordinates'][0]: 
    lat, long = tweet['geo']['coordinates'][:2] 
    print u'@%s: %s' % (user, tweet_text), lat, long 
else: 
    print u'@%s: %s' % (user, tweet_text) 

writer.writerow([user.encode('utf8'), time.encode('utf8'), 
       tweet_text.encode('utf8'), lat, long]) 
+0

哇! 我会发送评论给图书馆的作者,如果它可以帮助别人。 谢谢。 – Flo 2015-03-13 18:50:02

+0

Ooops :)完成了!再次感谢你。 – Flo 2015-03-13 18:58:03