Jademalo
Jademalo

Reputation: 3

Creating a twitter bot - Need help extracting a string

I'm pretty new to , and I don't know the best way to go about doing this. I've searched around, and I've solved most of my problems, but not this specific one.

I have a text file filled with random poems. For the purpose of testing, it's lorem ipsum. What I want to do is to extract a 140 character section out of this that is random. However, I only want it to include full words, so chop off the start and end up to the space.

eg.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent convallis nibh vitae ante dictum gravida. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque accumsan ante, quis porttitor libero tincidunt vel. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ullamcorper ornare metus quis pulvinar. Nullam at magna mauris. Aenean nec arcu odio.

Using the bot, I might extract:

tibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque accumsan ante, quis porttitor liber

Which would then be truncated to:

ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque accumsan ante, quis porttitor

Essentially I'm trying to create a horse_ebooks like bot that takes random strings of random words from a file and posts them onto twitter. I've got the posting all sorted out, I just need the method of extracting the string.

Upvotes: 0

Views: 231

Answers (2)

Fernando Freitas Alves
Fernando Freitas Alves

Reputation: 3777

 from random import random:

text = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent convallis nibh vitae ante dictum gravida. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque accumsan ante, quis porttitor libero tincidunt vel. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent ullamcorper ornare metus quis pulvinar. Nullam at magna mauris. Aenean nec arcu odio."""

poem_init = int(random()*(len(text)-140))
poem = text[poem_init:poem_init+140].split(" ")

if text.find(" "+ poem[0]) < 0:
    del poem[0]

if text.find(poem[-1] + " ") < 0 or text.find(poem[-1]) != len(text):
    del poem[-1]

poem = " ".join(poem)
print poem

Upvotes: 1

nucleartide
nucleartide

Reputation: 3988

You could extract the first 140 characters of a poem.

final_poem = poem_string[:140]

Then to make things simple, you could find the location of the last space, and cut off everything from that space onward.

for i, char in enumerate(reversed(final_poem)):
    if char == ' ':
        chop = i + 1 # Remember indices start with 0
final_poem = final_poem[:-chop]

Probably not the most efficient code, but it gets the job done.

Upvotes: 0

Related Questions