是否可以使用python交换文本文件中的两行文本?

问题描述 投票:-5回答:1

我正在尝试编写一个python脚本,该脚本将接收一个文件(我们称其为input.txt),并寻找以文本“移动到第一个边界点”结尾的行。然后,需要用该行之后的行替换该行,并用第一行替换它的行。文件的其余部分必须保持不变。文件中有很多实例需要执行此操作。

我的思考过程就是这样。查找以“移动到第一个边界点”结尾的线。一旦代码找到它,它将把该行保存为变量,然后从文件中删除该行。然后,如果下一行以“ restore layer Z”结尾(下一行总是如此),则需要在该行之后添加先前删除的行。

这是我想要做的:

  1. 打开文件('input.txt')。
  2. 交换每次出现的两个连续行,其中,
    • 第一行以:'move to first perimeter point'结尾
    • 第二行以:'restore layer Z'结尾
    • :众所周知,所有此类事件将始终成对发生(第一到第二行连续放置)。
  3. 将此更改写入新文件('output.txt')。

我曾尝试使用python将其放在一起。我几年前玩过python,模糊地记得如何使用它。它引发了错误。这是我在注释部分中建议的更正后的代码:(a)str.endwith --> str.endswith,(b)For --> for。任何建议都将非常有帮助和赞赏。

inp = open('input.txt','r')
out = open('output.txt', 'w')
prev = inp.readline()
for line in inp:
    if line.endswith('move to first perimeter point')
        prev = line
        if line.endswith('restore layer Z')
            out.write(line)
            out.write(prev)
    else:
        out.write(prev)
    prev = line
out.write(prev)
out.close()
inp.close

我希望输入文件保持不变,而创建新的输出文件。相反,什么也没发生。

谢谢您的帮助!我对此很陌生。

python pandas text-files swap text-processing
1个回答
0
投票

解决方案

这里我们将txt文件中的行读入变量s(字符串列表)。然后,自定义函数swap_lines_in_text()进行交换,并返回数据帧df进行进一步处理(如果需要)。最后,您可以使用df.Text.tolist()将其转换为行列表,然后使用file.writelines()将其写入新文件,如下所示。由于没有提供示例数据,所以我制作了自己的数据(请参阅下面的“虚拟数据”)。为了测试解决方案,我将使用伪数据。

# Read-in the lines from input file
with open('input.txt', 'r') as f:
    s = f.readlines()

# Execute Swap
df = swap_lines_in_text(s, 
                        first_line_text = 'move to first perimeter point', 
                        second_line_text = 'restore layer Z')

# Show output (comment out the following line if need be)
# print(df)
print('\n'.join(df.Text.tolist()))

# Write to output file
with open('output.txt', 'w') as f:
    f.writelines(df.Text.tolist())

输出

A
B
D restore layer Z
C move to first perimeter point
E
F
H restore layer Z
G move to first perimeter point
I
K restore layer Z
J move to first perimeter point
L
M
N

用于处理文本的自定义功能(目标行交换)

此函数将返回pandas.DataFrame对象。

import pandas as pd

def swap_lines_in_text(s, first_line_text='move to first perimeter point', second_line_text='restore layer Z'):
    """
    s = string or a list of strings.
    """
    if isinstance(s, list):
        lines = s.copy()
    else:
        lines = s.strip().split('\n')
    df = pd.DataFrame({'Text': lines})
    df.Text = df.Text.str.strip()
    # Detect Target Lines (both first and second kinds)
    first_lines = df.Text.str.contains(first_line_text)
    second_lines = df.Text.str.contains(second_line_text)
    # Swap lines
    df.Text.loc[first_lines], df.Text.loc[second_lines] = df.Text[second_lines].tolist(), df.Text[first_lines].tolist()
    return df

虚拟数据

s = """
A 
B 
C move to first perimeter point 
D restore layer Z
E 
F 
G move to first perimeter point
H restore layer Z
I 
J move to first perimeter point
K restore layer Z
L 
M 
N
"""
print(s.strip())
© www.soinside.com 2019 - 2024. All rights reserved.