【问题标题】:python csv module read data from headerpython csv模块从标头读取数据
【发布时间】:2014-09-29 17:17:54
【问题描述】:

我有以下格式的文件

# Data set number 1 
#
# Number of lines 4010
# Max number of column 3 is 5
# Blahblah
# More blahblah
1 2 1 110 
2 2 5 20 21 465 417 38
2 1 2 33 46 17
......
4010 3 5 1001 2010 3355 107 2039
# Data set number 2 
#
# Number of lines 4010
# Max number of column 3 is 5
# Blahblah
# More blahblah
1 2 1 110 
2 2 5 20 21 465 417 38
2 1 2 33 46 17
......

我希望读取数据集的数量、行数和第3列的最大数量。我搜索并发现csv模块可以读取标题,但是我可以读取这些标题的数量并存储吗?我所做的是

nnn = linecache.getline(filename, 1)
nnnn = nnn(line.split()[4])
number = linecache.getline(filename, 3)
number2 = number(line.split()[4])
mmm = linecache.getline(filename, 5)
mmmm = mmm(line.split()[7])
mmmmm = int(mmmm)
max_nb = range(mmmmm)
n_data = int(nnnn)
n_frame = range(n_data)
singleframe = natoms + 6

像这样。如何读取这些数字并使用 csv 模块存储?我使用“单帧”跳过了 6 个标题行,但也很好奇 csv 模块如何读取 6 个标题行。谢谢

【问题讨论】:

  • 这里不需要 csv
  • 不确定您希望linecache 在这里为您做什么;它是 Python 源代码自省工具,不是通用包。
  • @njzk2 嗯,他们只是使用 linecache 和 line split 就可以了吗?
  • @MartijnPieters 我之所以使用 linecache 是为了读取特定的标题行。

标签: python csv


【解决方案1】:

您实际上没有 CSV 文件;你有一个专有格式。直接解析即可,使用正则表达式快速提取你想要的数据:

import re

set_number = re.compile(r'Data set number (\d+)'),
patterns = {
    'line_count': re.compile(r'Number of lines (\d+)'),
    'max_num': re.compile(r'Max number of column 3 is (\d+)'),
}

with open(filename, 'r') as infh:
    results = {}
    set_numbers = []

    for line in infh:
        if not line.startswith('#'):
            # skip lines without a comment
            continue

        set_match = set_number.match(line)
        if set_match:
            set_numbers.append(int(set_match.group(1)))
        else:
            for name, pattern in patterns.items():
                match = pattern.search(line)
                if match:
                    results[name] = int(match.group(1))

不要使用linecache 模块。它将整个文件读入内存,实际上只用于访问 Python 源文件;每当需要打印回溯时,此模块都会缓存与当前堆栈相关的源文件。您只会将它用于需要随机行的较小文件,反复使用。

【讨论】:

  • 感谢有关 linecache 的建议。在我的文件中,我的数据集编号将是数组,但第 3 列的行数和最大数是单个数字。我怎样才能储存这个?就像'nlines = 4010'
  • @user1798797:您的意思是您需要阅读所有Data set 行?
  • @user1798797:代码现在将读取 all Data set 数字,并将它们收集到一个列表中。
  • 我希望得到“n_data = 2390(因为我的文件中有2390个'数据集')”并得到“n_lines = 4010”。我可以使用“ary = range(n_data)”来制作数组,但我只是希望将这些数据数、行数存储为单个名称
  • @user1798797:抱歉,我不太明白这一点。也许您可以使用预期的输出更新您的问题?
猜你喜欢
  • 2021-03-26
  • 2013-12-12
  • 2017-12-07
  • 2015-01-24
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 2016-07-31
相关资源
最近更新 更多