python - 提取包含特定名称的列

标签 python text-files extraction

我正在尝试使用它来处理大型 txt 文件中的数据。

我有一个包含 2000 多列的 txt 文件,其中大约三分之一的标题包含“Net”一词。我只想提取这些列并将它们写入新的 txt 文件。关于如何做到这一点有什么建议吗?

我搜索了一下,但未能找到对我有帮助的东西。如果之前提出并解决了类似的问题,我们深表歉意。

编辑 1:谢谢大家!在撰写本文时,已有 3 位用户提出了解决方案,而且它们都运行良好。老实说,我认为人们不会回答,所以我有一两天没有检查,对此感到很高兴。我印象深刻。

编辑 2:我添加了一张图片,显示了原始 txt 文件的一部分可能是什么样子,以防将来对任何人有帮助:

Sample from original txt-file

最佳答案

执行此操作的一种方法,无需安装像 numpy/pandas 这样的第三方模块,如下所示。给定一个名为“input.csv”的输入文件,如下所示:

a,b,c_net,d,e_net

0,0,1,0,1

0,0,1,0,1

(去掉中间的空行,它们只是为了格式化 这篇文章中的内容)

下面的代码可以满足您的需求。

import csv


input_filename = 'input.csv'
output_filename = 'output.csv'

# Instantiate a CSV reader, check if you have the appropriate delimiter
reader = csv.reader(open(input_filename), delimiter=',')

# Get the first row (assuming this row contains the header)
input_header = reader.next()

# Filter out the columns that you want to keep by storing the column
# index
columns_to_keep = []
for i, name in enumerate(input_header):
    if 'net' in name:
        columns_to_keep.append(i)

# Create a CSV writer to store the columns you want to keep
writer = csv.writer(open(output_filename, 'w'), delimiter=',')

# Construct the header of the output file
output_header = []
for column_index in columns_to_keep:
    output_header.append(input_header[column_index])

# Write the header to the output file
writer.writerow(output_header)

# Iterate of the remainder of the input file, construct a row
# with columns you want to keep and write this row to the output file
for row in reader:
    new_row = []
    for column_index in columns_to_keep:
        new_row.append(row[column_index])
    writer.writerow(new_row)

请注意,没有错误处理。至少有两个应该处理。第一个是检查输入文件是否存在(提示:检查 os 和 os.path 模块提供的功能)。第二个是处理空行或列数不一致的行。

关于python - 提取包含特定名称的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30029316/

相关文章:

python - 在 Python 中读取 Delphi 二进制文件

java - 获取 ArrayList 并将其放入文本文件中

python - 如何在不在 python 中提取 gz 文件的情况下列出它的内容?

python - 从一个部分中提取一个单词加上 20 个以上的单词(python)

python - Pandas 结合了 VLOOKUP 和 HLOOKUP 或者如何在矩阵中选择一个值

python - 重新索引数据框 Pandas

python - 使用索引和名称列重命名索引

python - 使用 Python 从一个文本文件复制到另一个文本文件

c - 如何用C语言将文件中的数据存储到数组中

java - 如何从 MP3 中获取音频数据?