我正在寻找从Twitter API中提取数据并创建一个管道分离文件,我可以对其进行进一步处理。我的代码目前看起来像这样:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
out_file = "tweets.txt"
tweets = api.search(q='foo')
o = open(out_file, 'a')
for tweet in tweets:
id = str(tweet.id)
user = tweet.user.screen_name
post = tweet.text
post = post.encode('ascii', 'ignore')
post = post.strip('|') # so pipes in tweets don't create unwanted separators
post = post.strip('\r\n')
record = id + "|" + user + "|" + post
print>>o, record
当用户的推文包含换行符时,我会遇到问题,这会导致输出数据如下所示:
473565810326601730|usera|this is a tweet
473565810325865901|userb|some other example
406478015419876422|userc|line
separated
tweet
431658790543289758|userd|one more tweet
我想在第三条推文上删除换行符。除了上述内容之外,我还尝试了post.strip(' \ n')和post.strip(' 0x0D 0x0A'),但似乎都没有效果。有什么想法吗?