2017-07-30 96 views
1

我想合併2個文件。第一個文件(co60.txt)僅包含整數值,第二個文件(bins.txt)包含浮點數。在Python中合併文件

co60.txt:

11 
14 
12 
14 
18 
15 
18 
9 

bins.txt:

0.00017777777777777795 
0.0003555555555555559 
0.0005333333333333338 
0.0007111111111111118 
0.0008888888888888898 
0.0010666666666666676 
0.0012444444444444456 
0.0014222222222222236 

當我合併這兩個文件與此代碼:

with open("co60.txt", 'r') as a: 
    a1 = [re.findall(r"[\w']+", line) for line in a] 
with open("bins.txt", 'r') as b: 
    b1 = [re.findall(r"[\w']+", line) for line in b] 
with open("spectrum.txt", 'w') as c: 
    for x,y in zip(a1,b1): 
     c.write("{} {}\n".format(" ".join(x),y[0])) 

我得到:

11 0 
14 0 
12 0 
14 0 
18 0 
15 0 
18 0 
9 0 

看起來,當我合併這兩個文件時,此代碼僅合併文件bins.txt的四捨五入值。

如何獲取的文件合併是這樣的:

11 0.00017777777777777795 
14 0.0003555555555555559 
12 0.0005333333333333338 
14 0.0007111111111111118 
18 0.0008888888888888898 
15 0.0010666666666666676 
18 0.0012444444444444456 
9 0.0014222222222222236 
+3

爲什麼你需要RegEx? 無論如何,你的問題是你的正則表達式不能匹配'。'字符,請考慮使用'[0-9 \。] +'模式 – immortal

+0

您能否用正確的代碼寫一個答案?我是編程新手。 – Afel

回答

2

正如提到的@immortal,如果你想使用正則表達式,然後使用 -

b1 = [re.findall(r"[0-9\.]+", line) for line in b] 
3

你可以不用正則表達式::

內容 spectrum.txt
with open("co60.txt") as a, open("bins.txt") as b, \ 
    open("spectrum.txt", 'w') as c: 
    for x,y in zip(a, b): 
     c.write("{} {}\n".format(x.strip(), y.strip())) 

11 0.00017777777777777795 
14 0.0003555555555555559 
12 0.0005333333333333338 
14 0.0007111111111111118 
18 0.0008888888888888898 
15 0.0010666666666666676 
18 0.0012444444444444456 
9 0.0014222222222222236