[英]Combination of lines from two text files
我有一个文本文件t1.txt
:
1¶
2¶
3
我有一个文本文件t2.txt
:
»1¶
»2¶
»3
其中»
和¶
分别代表制表符和换行符。
我想将两者结合起来并生成所有可能的组合:
11¶
12¶
13¶
21¶
22¶
23¶
31¶
32¶
33¶
这是我的代码:
out = 'out.txt'
in1 = 't1.txt'
in2 = 't2.txt'
outFile = open(out,'w')
with open(in1, 'r') as f:
for line1 in f:
for line2 in open(in2, 'r'):
outFile.write(line1+line2)
outFile.close()
但是我得到的输出是:
1¶
»1¶
1¶
»2¶
1¶
»32¶
»1¶
2¶
»2¶
2¶
»33»1¶
3»2¶
3»3
我不理解为什么。
有人可以帮忙吗?
您想要的产品 :
f1,f2 = "123","123"
from itertools import product
print(list(product(*(f1, f2))))
因此,对于您的文件:
with open("a.txt") as f1, open("b.txt") as f2:
print(list(product(*(map(str.rstrip,f1), map(str.rstrip,f2)))))
这会给你:
[('1', '1'), ('1', '2'), ('1', '3'), ('2', '1'), ('2', '2'), ('2', '3'), ('3', '1'), ('3', '2'), ('3', '3')]
并加入:
print(list(map("".join, product(*(map(str.rstrip,f1), map(str.rstrip,f2))))))
['11', '12', '13', '21', '22', '23', '31', '32', '33']
写入文件:
with open("a.txt") as f1, open("b.txt") as f2, open("out.txt", "w") as out:
for p in product(*(map(str.rstrip,f1), map(str.rstrip, f2))):
out.write("".join(p) + "\n")
输出:
11
12
13
21
22
23
31
32
33
对于python2,请使用itertools.imap
:
product(*(imap(str.rstrip,f1),imap(str.rstrip, f2))
您的行包含换行符和空格。 这些在行尾不可见。
您必须清除以下字符:
out = 'out.txt'
in1 = 't1.txt'
in2 = 't2.txt'
with open(in2, 'r') as f:
lines2 = [l.rstrip() for l in f]
with open(out,'w') as outFile:
with open(in1, 'r') as f:
for line1 in f:
line1 = line1.rstrip()
for line2 in lines2:
outFile.write(line1+line2+'\n')
文件中有空格和返回。 使用strip()修剪它们
out = 'out.txt'
in1 = 't1.txt'
in2 = 't2.txt'
outFile = open(out,'w')
with open(in1, 'r') as f:
for line1 in f:
for line2 in open(in2, 'r'):
outFile.write(line1.strip()+line2.strip()+"\n")
outFile.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.