Python 如何读取格式不均匀的文件?
我有这样的文件格式Python 如何读取格式不均匀的文件?,python,regex,Python,Regex,我有这样的文件格式 9 0.0351562 0.0713449-11.4664-25.9366-27.955 4 2.38188 10 0.0390625 0.0507383 -12.9466 -30.2437 -29.1045 4 0.616179 11 0.0429688 0.0629145 -12.0125 -37.1503 -32.2795 4 0.569045 12 0.046875 0.046937 -13.2848 -31.9606 -32.5367 4 0.128286 13 0
9 0.0351562 0.0713449-11.4664-25.9366-27.955 4 2.38188
10 0.0390625 0.0507383 -12.9466 -30.2437 -29.1045 4 0.616179
11 0.0429688 0.0629145 -12.0125 -37.1503 -32.2795 4 0.569045
12 0.046875 0.046937 -13.2848 -31.9606 -32.5367 4 0.128286
13 0.0507812 0.0541174 -12.6666 -30.7398 -27.4705 4 1.38345
关于Python代码,我的想法是使用正则表达式
for line in s.splitlines():
lst = [i.strip() for j in re.findall(regex, line) for i in j if j]
print(lst)
但是正则表达式应该是什么样子呢?写入文件的C代码行:
fprintf(inf),“%d%g%g%g%g%g%g%g\n”,i,frq1,
规范[i]、dbspec、naive_规范[i]、dtemp[i],
自由度[i],f值[i];
在Python语法中,我有8个变量,1个整数和7个双精度。我不会使用正则表达式,因为这些值都是以空格分隔的。下面介绍如何使用
split()
string方法:
with open('path/to/file') as infile:
for line in infie:
nums = [float(i) for i in line.split()]
# do stuff with nums
kinds = [int] + [float]*7 # types expected
with open('uneven.txt') as file:
for line in file:
row = map(lambda v: v[0](v[1]), zip(kinds, line.split()))
print(row)