Предположим, у меня есть список строк, и я хотел сделать из них твит. Например:
# 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" ]
мой желаемый результат будет похож на этот (конечно, сохраненный в списке):
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'
Я пытался использовать цикл while для достижения этого, но я не уверен, что цикл работает правильно...
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))
Вы также не добавляете пробелы между словами и не учитываете эти пробелы при расчете s
.
Добавьте несколько операторов печати в свой код, чтобы увидеть, что происходит не так. Вы можете решить свою проблему самостоятельно.
сделал несколько обновлений @Johnny Mopp, я изначально тоже это учитывал. Также твиттер не считает пробел символом.
@blarg моя лучшая попытка приблизила меня к желаемому результату; но оно добавляло одно и то же слово снова и снова, как указал Джонни Мопп
Это не самый пифонический способ сделать это. Но это довольно ясно и наглядно разбивает логику:
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 (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)
В итоге я использовал список кортежей, содержащих длину и текст; затем суммируя длины, пока не встретится 140 символов.
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
tweet += x
- Вы просто добавляете одно и то же слово снова и снова, покаs >= 140
. Попробуйте поменять местами петлиwhile
иfor
. Или, может быть, удалитьwhile
.