我在使用python reg exp从文件中读取数据时遇到了麻烦。
该文件包含我想要的数据和一些我不感兴趣的信息。我感兴趣的信息示例如下。行数会有所不同
FREQ VM(VOUT)
1.000E+00 4.760E+01
1.002E+00 4.749E+01
Y
我想创建一个元组列表,如:
[(1.000, 47.6),(1.002, 47.49)]
我正在尝试读取文件,直到找到'FREQ VM(VOUT)'行并读取数据点,直到我点击'Y'。
我有两个问题:
我找不到一个与我正在做的非常接近的例子。如果它在那里,请指出它。
答案 0 :(得分:3)
我认为这会让你得到你想要的东西。只要文件一致。
from csv import reader
with open('file') as f:
listoftuples = [(float(row[0]), float(row[1]))
for row in reader(f, delimiter=' ')
if row and row[0] != 'FREQ']
如果你希望它在'Y'处打破,那么这样做不那么优雅:
from csv import reader
l = []
with open('file') as f:
for row in reader(f, delimiter=' '):
if row[0] == 'Y':
break
if row and row[0] != 'FREQ':
l.append((floar(row[0]), float(row[1])))
答案 1 :(得分:1)
import decimal
flag=0
result=[]
for line in open("file"):
line=line.rstrip()
if line == "Y": flag=0
if line.startswith("FREQ VM"):
flag=1
continue
if flag and line:
result.append(map(decimal.Decimal,line.split()))
print result
答案 2 :(得分:0)
不如Tor's answer那么优雅。也没有正则表达式。带上downvotes!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import decimal
import os
def main():
we_care = False # start off not caring
list_of_tuples = []
f = open('test.txt','r')
for line in f:
if line.startswith('FREQ'):
we_care = True # we found what we want; now we care
continue
if we_care:
try:
x,y = (decimal.Decimal(x)
for x in line.rstrip(os.linesep).split())
list_of_tuples.append((x,y))
except ValueError:
pass # we get here when a line doesn't contain two floats
except decimal.InvalidOperation:
pass # we get here when a line contains a non-decimal
if line.startswith('Y'):
break # break out of processing once you've got your data
return list_of_tuples
if __name__ == "__main__":
print main()
返回:
[(Decimal('1.000'), Decimal('47.60')), (Decimal('1.002'), Decimal('47.49'))]