简体   繁体   English

可以将读取的文件与列表切片一起组合在列表理解中吗?

[英]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. 以下代码片段是使用Twython的Twitter机器人的核心。 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. 我检查了一下,找到了一些示例,例如使用readlines()读取整个文件,但也没有涉及切片的示例。

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 2.7,Linux。 Python 3.5 is installed & available if needs be. Python 3.5已安装并在需要时可用。

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). 使用readline()。strip()是因为我希望能够读取具有任意长度的行的文件并删除任何EOL和空格(列表的最后一项只能以空格结尾; twitter将拒绝状态更新空格,而我尚未为此编写任何错误处理)。

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 我认为这是我有限的技能最简单的解决方案,因为该机器人无法全天候运行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. 我不是程序员,我使用了在Stack Overflow和其他地方发现的示例代码片段来破解这些代码。 I'm trying to use quite simple code and not rely on 3rd party libs apart from Twython. 我正在尝试使用非常简单的代码,而不依赖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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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