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

2024-03-28

我正在寻找从 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') 但似乎都不起作用。有任何想法吗?


那是因为strip https://docs.python.org/2/library/string.html#string.strip返回“字符串的副本leading and trailing字符被删除”。

你应该使用replace https://docs.python.org/2/library/string.html#string.replace对于新线路和管道:

post = post.replace('|', ' ')
post = post.replace('\n', ' ')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐