我目前正在尝试使用TwitterSearch(https://github.com/ckoepp/TwitterSearch)将推文导入csv进行分析。但是,我在执行python脚本时收到以下错误消息:
from .TwitterSearchException import TwitterSearchException
ValueError: Attempted relative import in non-package
以下是代码:
from TwitterSearch import *
from TwitterSearchException import *
import csv
def get_tweets(query, max_tweets):
query = raw_input ("Search for:")
max_tweets = 2000
# takes a search term (query) and a max number of tweets to find
# gets content from twitter and writes it to a csv bearing the name of your query
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_language('en') # English tweets only
ts = TwitterSearch(
consumer_key = '',
consumer_secret = '',
access_token = '',
access_token_secret = ''
)
for tweet in ts.search_tweets_iterable(tso):
lat = None
long = None
time = tweet['created_at'] # UTC time when Tweet was created.
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)
感谢您的帮助!
答案 0 :(得分:0)
尝试对TwitterSearchException
行进行更具体的导入,而不是*
。
答案 1 :(得分:0)
怎么样
from TwitterSearch.TwitterSearchException import TwitterSearchException
TwitterSearchException
不是python包,TwitterSearch
是。