删除python中每行中的第一个单词

时间:2015-11-23 10:20:17

标签: python-3.x

我的文本文件目前如下所示:

1 1.094141 -19.991062 -0.830169
2 0.506693 -19.613609 -2.876364
3 -0.355470 -18.932575 -4.884786
4 -0.354663 -27.707542 -21.295307
5 1.008405 -18.191206 -4.542386
6 2.663746 -19.178164 -5.195459
10 0.245458 -17.983212 -2.999652
11 1.411953 -20.360981 -4.684113

我需要一个程序来删除每行中的第一个字符,使其看起来像:

1.094141 -19.991062 -0.830169
0.506693 -19.613609 -2.876364
-0.355470 -18.932575 -4.884786
-0.354663 -27.707542 -21.295307
1.008405 -18.191206 -4.542386
2.663746 -19.178164 -5.195459
0.245458 -17.983212 -2.999652
1.411953 -20.360981 -4.684113

我如何在Python中执行此操作?我有超过200个具有类似数据的文件,我需要删除第一个字符。请帮我解释一下代码。谢谢! :)

好吧,我也在尝试做其他事情,但我想修复我的代码中的逻辑。

import numpy as np

with open('test2.txt') as f1:
    lines = f1.readlines()

with open('test2.txt') as infile:

    with open('Output.txt', 'a') as outfile:
        outfile.write('# vtk Datafile Version 3.0 \n')
        outfile.write('Unstructured Grid.. \n')
        outfile.write('ASCII\n')

        copy = False
        for line in infile:

            if line.strip() == "651734":
                copy = True
            elif line.strip() == "$EndNodes":
                copy = False
            elif line.strip() == "3089987":
                copy = True
            elif copy:
                outfile.write(line)

1 个答案:

答案 0 :(得分:1)

以下几行会将您提供的行拆分为代码第4行的lines变量,并删除第一个空格之前的单词。

for line, i  in enumerate(lines):
    lines[i] = line.split(" ", 1)[1]

请注意,仅当您的线条始终遵循上述布局时,此功能才有效。

了解如何正确使用拆分here 当然,再仔细研究python文档。

话虽如此,看起来第二个with open(test2.txt)也是多余的;你已经在第4行的lines变量中存储了该文件的行,所以就在那里你只是在浪费空间和内存。

在继续编写程序之前,您应该再次勾勒出自己的想法。现在它很冗余,而且没有经过深思熟虑。