【问题标题】:Stripping Line Breaks in Tweets via Tweepy通过 Tweepy 去除推文中的换行符
【发布时间】:2014-08-17 12:33:48
【问题描述】:

我正在从 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') 但似乎没有一个工作。有什么想法吗?

【问题讨论】:

    标签: python twitter tweepy


    【解决方案1】:

    这是因为strip 返回“删除了前导尾随字符的字符串副本”。

    您应该将replace 用于新行和管道:

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

    【讨论】:

    • 这似乎奏效了。谢谢。我不完全理解为什么替换适用于换行符而不适用于剥离,但我认为你已经为我指出了正确的方向。
    • 要删除的换行符位于字符串的中间,而不是字符串的末尾或开头。 strip 仅在您想从“边缘”中删除某些内容时才有效。
    猜你喜欢
    • 2018-06-26
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 2017-08-20
    • 2018-02-24
    • 2021-04-30
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多