如何在文本文件中合并每一行及其后续行

时间:2019-03-27 02:44:51

标签: python-2.7

我有一个文本文件 z.txt 。看起来像这样:

alcoholic
alert
algebra
alibi
blablabla
...

如何使用python使每一行看起来都像这样(与其后一行结合在一起):

alcoholic alert
alert algebra
algebra alibi
alibi blablabla
blablabla ...

我不完整的代码如下:

with open('z.txt','r') as inF:
    for line in inF:
        line =

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

我将构建一个包含所需输出行的列表。最后,我将这些行写入名为z_out.txt的文件中。

假设您的z.txt中包含以下内容。

  

z.txt

alcoholic
alert
algebra
alibi
blablabla

现在,您可以尝试这样。

  

construct.py

output_lines = []

with open("z.txt") as f:
    lines = f.readlines()
    l =  len(lines)

    if l <= 1:
        if l == 1:
            output_lines = lines[0]
    else:
        # strip() is to remove `\n` from end of `lines[index]`
        output_lines = [lines[index].strip() + ' ' + lines[index + 1] for index in range(l-1)]

print(output_lines)
# ['alcoholic alert\n', 'alert algebra\n', 'algebra alibi\n', 'alibi blablabla']

# If you wish to save it in a file named `z_out.txt`
with open("z_out.txt", "w") as f:
    f.writelines(output_lines)
  

z_out.txt

alcoholic alert
alert algebra
algebra alibi
alibi blablabla

答案 1 :(得分:1)

这里有可能使用列表理解,以列表的形式提供输出。

with open('z.txt','r') as f: 
    wordlist = f.read().split('\n')

>>>wordlist
['alcoholic', 'alert', 'algebra', 'alibi', 'blablabla']

combineduo = [' '.join([x.strip(), y.strip()]) for x,y in zip(wordlist[:-1],wordlist[1:])]

>>>combineduo
['alcoholic alert', 'alert algebra', 'algebra alibi', 'alibi blablabla']