通过Tweepy去除推文中的换行符

5 投票
1 回答
3582 浏览
提问于 2025-04-18 11:12

我想从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'),但是都没有效果。有没有什么好的办法?

1 个回答

4

这是因为 strip 方法会返回一个“去掉了开头和结尾字符的字符串副本”。

你应该使用 replace 方法来处理换行符和管道符:

post = post.replace('|', ' ')
post = post.replace('\n', ' ')

撰写回答