2016-12-01 26 views
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, 
     spec[i],dbspec, naive_spec[i], dtemp[i], 
     dof[i], Fvalues[i]); 

我在第8級的變量,1個整數和Python語法7倍。

回答

2
with open('path/to/file') as infile: 
    for line in infie: 
     nums = [float(i) for i in line.split()] 
     # do stuff with nums 
1

因爲這些值都空格分隔我不會用正則表達式這一點。以下是如何使用split()字符串方法:

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)