简体   繁体   English

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

[英]Tweepy: Reading Text File and Tweeting Out Line Breaks in Each Tweet

Total beginner here, so thanks for your patience.这里是初学者,所以感谢您的耐心等待。 I'm trying to use Tweepy to read tweets from a text file and tweet them out.我正在尝试使用 Tweepy 从文本文件中读取推文并将其发送出去。 Pretty straightforward, but I want tweets from each line of the text file to have line breaks between them.非常简单,但我希望来自文本文件每一行的推文在它们之间有换行符。 For example, one tweet could look like this:例如,一条推文可能如下所示:

Part one of tweet推文第一部分

Part two of tweet推文第二部分

Part three of tweet推文第三部分

Again, the tweet is one line in the text file itself.同样,推文是文本文件本身中的一行。 I just want to break up some of the text in that line.我只是想分解该行中的一些文本。

In the text file, I created the tweets by inserting two "\n" between these line breaks, but the "\n" characters are showing up in the tweets themselves.在文本文件中,我通过在这些换行符之间插入两个“\n”来创建推文,但是“\n”字符显示在推文本身中。 So how do I create these line breaks in my tweets?那么如何在我的推文中创建这些换行符呢? Many thanks for your help.非常感谢您的帮助。

The \n s will not be line-feed characters when typed like that into a text editor, but they are line-feed characters in Python code. \n在文本编辑器中输入时不会是换行符,但它们是 Python 代码中的换行符。

The code below will break up your one-line tweets into three words per line with one line-feed character between each three-word line.下面的代码会将您的单行推文分解为每行三个单词,每行三个单词之间有一个换行符。

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)

Example:例子:

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)

Results in:结果是:

I'm going to
press enter every
three words just
to annoy you.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM