2

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. 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. So how do I create these line breaks in my tweets? Many thanks for your help.

Adam
  • 21
  • 2

1 Answers1

0

The \ns will not be line-feed characters when typed like that into a text editor, but they are line-feed characters in Python code.

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.
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223