Python:解析文本文件
我的文件如下所示: 2乘100的矩阵 我想为每列创建一个列表,其中一个列表对应于每行映射到当前的第一个元素,第二个元素映射到温度 如下图所示。有没有更好的方法让代码看起来更华丽Python:解析文本文件,python,parsing,Python,Parsing,我的文件如下所示: 2乘100的矩阵 我想为每列创建一个列表,其中一个列表对应于每行映射到当前的第一个元素,第二个元素映射到温度 如下图所示。有没有更好的方法让代码看起来更华丽 -12,30 -34,50 -33,89 -900,9 -2,37 -7,17 -8,28 -12,30 -34,50 -33,89 def parse_log(fname): f = open(fname, "r") samples = f.readlines() samples = filt
-12,30
-34,50
-33,89
-900,9
-2,37
-7,17
-8,28
-12,30
-34,50
-33,89
def parse_log(fname):
f = open(fname, "r")
samples = f.readlines()
samples = filter(lambda x: not x.startswith('*'), samples)
print(samples)
current = map(lambda x: -1 * int(x.split(',')[0]), samples)
print(current)
temperature = map(lambda x: int(x.split(',')[1]), samples)
print(temperature)
return (current, temperature)
使用生成器表达式:
def parse_log(fname):
with open(fname, "r") as file:
return zip(*(
(int(current) * -1, int(temp)) for current, temp in
(line.strip().split(',')
for line in file if not line.startswith('*'))
))
print parse_log(filename)
[(-12, -34, -33, -900, -2, -7, -8, -12, -34, -33), (30, 50, 89, 9, 37, 17, 28, 30, 50, 89)]
警告,这并不一定更好,因为它可能更难阅读和理解正在发生的事情。一定要用docstring正确地记录它。为了避免对每行执行两次
拆分调用,我建议以下解决方案
def parse_log(fname):
with open(fname) as f:
samples = [line.strip() for line in f.readlines()
if not line.startswith('*')]
ints = [map(int, line.split(",")) for line in samples]
currents = [-x[0] for x in ints]
temperatures = [x[1] for x in ints]
return currents, temperatures
这是一个简单的版本,最多可以使用几兆字节的日志文件(它不尝试在解析期间最小化内存使用或计算时间):
使用lambda
避免map
和filter
。使用理解。你的答案不使用任何列表理解。你也没有纠正电流的负值。对不起,更改了我的答案,但没有更改我的文本。修正了文本:)啊,他没有把它放在他的需求中,我在代码中忽略了它。zip(*(abs(int(current)),int(temp))表示当前,temp in(line.split(','))表示f中的行,如果不是line.startswith('*'))
def parse_log(fname):
data = [map(int, x.split(",")) for x in open(fname) if x[:1] != "*"]
return ([-current for current, temp in data],
[temp for current, temp in data])