简体   繁体   English

从txt文件的列表中删除指定的元素

[英]Remove specified elements from a list in a txt file

I have a text file with a 1825 x 51 table. 我有一个1825 x 51表格的文本文件。 I am attempting to read into the text file and write this table to a new text file while removing certain columns from the table. 我试图读入文本文件并将此表写入新的文本文件,同时从表中删除某些列。 I couldn't figure out how to delete a whole column because the list is a string so I am attempting to go into each row and use an if/else statement to determine if the element is in the desired range. 我无法弄清楚如何删除整列,因为列表是一个字符串,所以我尝试进入每一行并使用if / else语句确定元素是否在所需范围内。 If it is, write it to output, otherwise delete it. 如果是,请将其写入输出,否则将其删除。

 if i in range(1,3)+[14]+range(20,27)+range(33,38)+[43]+[45]:
     newNum=data[i]
     data[i]=newNum
 else:
     delete.data

This is my first time using python so any help would be greatly appreciated! 这是我第一次使用python,因此任何帮助将不胜感激!

code from comments 注释中的代码

with open(inputfilepath,'r') as f:
    outputfile=open(outputfilepath,'w+')
    inSection=False
    for line in f:
        if begin in line:inSection=True
        if inSection:
            keep=range(1,3)+[14]+range(20,27)+range(33,38)+[43]+[45]
            tmp=[]
            spl=line.split('  ')
            for idx in keep:
                tmp.extend(spl[idx])
            outputfile.write('%s\n' % '  '.join(tmp))            
        if end in line:inSection=False
keep = [1,2,3,14,20,21,22,23,24,25,26,27,33,34,35,36,37,38,43,45]
with open('textfile') as fin, open('textout') as fout:
   for ln in fin:
       tmp = []
       spl = ln.split(' ')
       for idx in keep:
           tmp.append(spl[idx])
       fout.write('%s\n' % ' '.join(tmp))

I would probably go with something like this: 我可能会喜欢这样的东西:

from __future__ import print_function


def process(infile, keep):
    for line in infile:
        fields = line.split()
        yield ' '.join([_ for i, _ in enumerate(fields) if i in keep])


def main(infile, outfile):
    # The following line (taken from your example) will not work in Python 3 as
    # you cannot "add" ranges to lists. In Python 3 you would need to write:
    # >>> [14] + list(range(20, 27)
    keep = range(1, 3) + [14] + range(20, 27) + range(33, 38) + [43] + [45]
    for newline in process(infile, keep):
        print(newline, file=outfile)


if __name__ == '__main__':
    with open('so.txt') as infile, open('output.txt', 'w') as outfile:
        main(infile, outfile)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM