Tweepy:读取文本文件并在每条推文中推出换行符

问题描述 投票:2回答:1

这里是初学者,非常感谢您的耐心配合。我正在尝试使用Tweepy从文本文件中读取鸣叫并将其鸣叫出去。非常简单,但是我希望文本文件中每一行的推文之间可以有换行符。例如,一条推文可能如下所示:

tweet的第一部分

推文的第二部分

推文的第三部分

同样,tweet是文本文件本身中的一行。我只想分解该行中的一些文本。

[在文本文件中,我通过在这些换行符之间插入两个“ \ n”来创建了tweets,但是这些“ \ n”字符却显示在tweets本身中。那么如何在推文中创建这些换行符?非常感谢您的帮助。

python twitter text-files tweepy
1个回答
0
投票

[\n在文本编辑器中键入时不会是换行字符,但是在Python代码中是换行字符。

下面的代码会将您的单行tweet分解为每行三个单词,每三个单词行之间有一个换行字符。

import tweepy

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

def chunks(lst, n):
    """Yield successive n-sized chunks from lst.
       from here: https://stackoverflow.com/a/312464/42346"""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

with open('to_be_tweeted.txt','r') as f:
    for line in f:
        split_on_spaces = line.rstrip('\n').split()
        chunked = [chunk for chunk in chunks(split_on_spaces,3)]
        multiline_tweet = "\n".join([" ".join(word for word in chunk) 
                                     for chunk in chunked])
        api.update_status(multiline_tweet)

示例:

s = """I'm going to press enter every three words just to annoy you."""
split_on_spaces = s.rstrip('\n').split()
chunked = [chunk for chunk in chunks(split_on_spaces,3)]
multiline_tweet = "\n".join([" ".join(word for word in chunk) 
                             for chunk in chunked])
print(multiline_tweet)

结果:

I'm going to
press enter every
three words just
to annoy you.
© www.soinside.com 2019 - 2024. All rights reserved.