2017-07-30 90 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