从python 3.x中的文件读取输入 [英] Reading input from a file in python 3.x
问题描述
假设您正在从结构类似的文件中读取输入
Say you are reading input from a file structured like so
P3
400 200
255
255 255 255
255 0 0
255 0 0
etc...
但是您要考虑输入文件中可能出现的任何错误,如
But you want to account for any mistakes that may come from the input file as in
P3 400
200
255
255 255
255
255 0 0
255 0
0
etc...
我想读第一个令牌"P3",然后读下两个"400","200"(高度/宽度)"255",从这里开始,我想读入每个令牌并说明它们的方式应该以3为一组.我具有读取此信息的正确代码,但似乎无法弄清楚如何通过令牌而不是逐行读取信息.
I want to read in the first token 'P3' then the next two '400' '200' (height/width) the '255' and from here on, I want to read every token in and account for how they should be in groups of 3. I have the correct code to read this information but I can't seem to get past the wall of figuring out how to read in information by token and not by line.
没有考虑输入不正确的情况.
Which doesn't account for an imperfect input.
推荐答案
如果您的文件由三个值组成的组(在第一个P3
项之后),并且您不能依靠换行符将它们正确分组,我建议将文件作为单个字符串读取,然后进行拆分和分组.这是简单明了的方法:
If your file consists of groups of three values (after the first P3
item) and you cannot rely upon the line breaks to have them grouped properly, I suggest reading the file as a single string and doing the splitting and grouping yourself. Here's a straight-forward way:
with open(filename) as f:
text = f.read() # get the file contents as a single string
tokens = text.split() # splits the big string on any whitespace, returning a list
it = iter(tokens) # start an iterator over the list
prefix = next(it) # grab the "P3" token off the front
triples = list(zip(it, it it)) # make a list of 3-tuples from the rest of the tokens
在同一引用的多个引用上使用zip
是这里的关键.如果需要使用相同的代码处理其他组大小,则可以使用zip(*[it]*grouplen)
.
Using zip
on multiple references to the same iterator is the key trick here. If you needed to handle other group sizes with the same code, you could use zip(*[it]*grouplen)
.
请注意,这将丢弃文件末尾的所有剩余值(如果它们不是三个组成的一组).如果您需要以不同的方式处理这种情况,建议您使用itertools
模块中的zip_longest
,而不是常规的zip
函数. (请参见 itertools
文档中的grouper
食谱 )
Note that this will discard any left-over values at the end of the file if they don't form a group of three. If you need to handle that situation differently, I suggest using zip_longest
from the itertools
module, rather than the regular zip
function. (See the grouper
recipe in the itertools
documentation.)
这篇关于从python 3.x中的文件读取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!