【问题标题】:Combination of lines from two text files来自两个文本文件的行组合
【发布时间】:2015-12-26 17:45:02
【问题描述】:

我有一个文本文件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

我不明白为什么。
有人可以帮忙吗?

【问题讨论】:

  • 嗨。看这里:iterools 并搜索组合()。
  • 你知道缩进不正确吗?
  • 第二个 for 循环嵌套在第一个循环内,这意味着它将打印第一个文件的每一行与第二个文件的每一行,然后打印第一个文件的第二行与每个第二行等。
  • @mic4ael 是的,很抱歉在复制粘贴时发生...
  • @martineau 为什么?它不会打印第一行的每一行和第二行吗?这不是嵌套循环的作用吗?我很困惑..

标签: python file text


【解决方案1】:

您的文件中有空格和回车符。使用 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()

【讨论】:

  • 非常感谢! :D 这既快速又简单.. :)
【解决方案2】:

你想要product:

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))

【讨论】:

  • 如果我从两个 BIG 文本文件中获取输入,我该怎么做?我想合并行..来自两个文件...
  • @418,我会编辑,但你只需对文件应用相同的逻辑
  • 非常感谢您的帮助!! :)
【解决方案3】:

您的行包含换行符和空格。这些在行尾是不可见的。

你必须清除这些字符:

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')

【讨论】:

    猜你喜欢
    • 2011-04-30
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多