如何在Python中合并一个文本文件的多行?

-1 投票
4 回答
752 浏览
提问于 2025-04-17 04:38

我搜索过,但没有找到任何能帮忙的东西……这是一个例子:

    List.txt
    a
    b
    c
    d

我想要得到这样的输出:

    Output.txt
    ab
    ac
    ad
    ba
    bc
    bd
    ca
    cb
    cd
    etc...

4 个回答

0
f = open("List.txt")
lines = f.read().splitlines()
lines_new = []
for line in lines:
    for line2 in lines:
        if not line == line2:
            lines_new.append("%s%s" % (line, line2))

print lines_new # ['ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc']
open("Output.txt", "w").write("\n".join(lines_new))

结果会保存在一个叫做 Output.txt 的文件里,内容是:

ab
ac
ad
ba
bc
bd
ca
cb
cd
da
db
dc
0

itertools模块提供了一些组合函数,可以帮助解决像这样的问题:

>>> from itertools import combinations, permutations, product
>>> s = open('list.txt').read().splitlines()
>>> for t in permutations(s, 2):
        print ''.join(t)
2

这很简单...

from itertools import permutations

with open('List.txt') as f:    
    letters = (l.strip() for l in f if l.strip())    
    for p in permutations(letters, 2):
        print ''.join(p)

输出结果:

ab
ac
ad
ba
bc
bd
ca
cb
cd
da
db
dc

一些说明:

with 语句确保在你用完文件后,它会被自动关闭。

letters 是一个生成器表达式,这在很多情况下(虽然这次不是)可以让你避免一次性读取整个文件。

使用 l.strip() 是为了好好处理输入中可能出现的空行。

itertools.permutations 是正确的选择,而不是 itertools.combinations,后者会把 abba 看作是相同的,不会把后者包含在输出中。

祝你编程愉快 :)

撰写回答