简体   繁体   中英

Can a file read be combined in a list comprehension with list slicing?

The following code fragment is the core of a twitter bot using Twython. I would like to know if I can combine the file read into the list comprehension as it seems rather convoluted to read a line in as a one-item list only to then create another multi-item list from that.

I've checked around and found some examples where a whole file is read in using readlines() for instance, but not one where slicing is involved too.

with open(tweet_datafile,'r') as smstweets:
    bigtweet = smstweets.readline().strip() 
    text_entire = [ bigtweet[i:i+140] for i in range(0,len(bigtweet),140) ]

for line in range(len(text_entire)):
    twitter.update_status(status=text_entire[line])

Notes:

Python 2.7, Linux. Python 3.5 is installed & available if needs be.

readline().strip() is used because I want to be able to read a file with lines of arbitrary length and remove any EOL and whitespace (the last item of the list could end up as spaces only; twitter will reject a status update of spaces, and I haven't yet written any error-handling for this).

I read only the first line of the input file and then later in the code write the file back out minus that line. I decided this was the simplest solution for my limited skills as the bot won't run 24/7

I'm not a programmer, I've hacked this together using scraps of example code I found lying about on Stack Overflow and elsewhere. I'm trying to use quite simple code and not rely on 3rd party libs apart from Twython. Generators and iterators appear as sorcery to me.

Well, maybe just a minor change - it is not necessary to assign the list to a variable nor to iterate over indices, the list can be iterated over directly :

with open(tweet_datafile,'r') as smstweets:
    bigtweet = smstweets.readline().strip() 
for line in ( bigtweet[i:i+140] for i in range(0,len(bigtweet),140) ):
    twitter.update_status(status=line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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