2017-07-30 11 views
1

2つのファイルをマージしたい。最初のファイル(co60.txt)は整数値のみを含み、2番目のファイル(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 

この2つのファイルをマージすると、このコードはファイル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 
関連する問題