Suppose i have a list of strings and I wanted to make a tweet out of them. for example:
# should be two tweets total
this_list = ["Today is monday tomorrow is tuesday the next" ,"will be friday and after that", "saturday followed by sunday", "this month is march the next", "april after that may followed", "by june then july then we", "have august then", "september and october finishing", "the year with november and december" ]
my desired output would be similar to this (stored in a list of course):
tweet 1: 'Today is monday tomorrow is tuesday the next will be friday and after that saturday followed by sunday this month is march the next april'
tweet 2: 'after that may followed by june then july then we have august then september and october finishing the year with november and december'
I have tried to use a while loop to achieve this but I am not sure the loop is working correctly...
out = [] # empty list
s = 0 # counter
tweet = "" # string to add too
while s < 140:
for x in this_list:
tweet = x
s = len(x)
out.append(tweet)
print(len(out))
CodePudding user response:
This is not the most pythonic way of doing this. But it is pretty clear and breaks down the logic in a visible manner:
mylist = ['Today', 'is', 'monday', 'tomorrow', 'is', 'tuesday', 'the', 'next', 'will', 'be', 'friday', 'and', 'after', 'that', 'saturday', 'followed', 'by', 'sunday', 'this', 'month', 'is', 'march', 'the', 'next', 'april', 'after', 'that', 'may', 'followed', 'by', 'june', 'then', 'july', 'then', 'we', 'have', 'august', 'then', 'september', 'and', 'october', 'finishing', 'the', 'year', 'with', 'november', 'and', 'december']
position = 0 #We keep track of the position, because we might reach the end of the list without meeting the 140 chars criteria
n_chars = 0 #character counting variable
list_of_tweets = []
iter_string = ''
for word in mylist:
if(n_chars < 140): #We keep adding words to our sentence as max number of chars is not reached
iter_string = iter_string word ' '
n_chars = n_chars len(word) 1 # 1 because of the space we add
if(n_chars >= 140):
list_of_tweets.append(iter_string[:-1]) #We delete the last char as it is a space
iter_string = ''
n_chars = 0
if(n_chars >= 140):
print('entra')
list_of_tweets.append(iter_string)
iter_string = ''
n_chars = 0
if(position == len(mylist)-1):
list_of_tweets.append(iter_string[:-1])
position = position 1 #We are advancing to the next word in the iteration
print(list_of_tweets)
CodePudding user response:
I ended up using a list of tuples that held the length and text; then summing through the lengths until 140 characters met.
lot = [(len(i),i) for i in output] # list of tuples (length, txt)
out = [] # store tweets
y=0 # count len of tweets
t= '' # empty tweet
for l, txt in lot:
y = l
t = txt
if y >= 140:
t= ''
y = 0
else:
if y>= 119: # I want the 'full tweet' not building blocks
print(t)
out.append(t)
len(out) #number of tweets