2014-09-29 96 views
0

我有以下文件的格式讀取數據蟒蛇CSV模塊從頭部

# 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模塊進行存儲?我使用'singleframe'跳過了6條標題,但也很好奇csv模塊如何讀取6條標題行。謝謝

+1

這裏不需要csv – njzk2 2014-09-29 17:25:51

+1

不確定你期望'linecache'在這裏爲你做什麼;它是一個Python源代碼內省工具,而不是一個通用的包。 – 2014-09-29 17:29:48

+0

@ njzk2嗯,他們只是使用linecache和行分裂是好的? – exsonic01 2014-09-29 17:32:40

回答

0

你真的沒有一個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源文件;無論何時需要打印回溯,本模塊都會緩存涉及當前堆棧的源文件。您只能將它用於需要重複使用隨機線的較小文件。

+0

感謝您提供有關linecache的建議。在我的文件中,我的數據集編號是數組,但是第3列的行數和最大數量是單個數字。我該如何儲存?就像'nlines = 4010' – exsonic01 2014-09-29 17:56:17

+0

@ user1798797:你的意思是你需要讀取所有'Data set'行? – 2014-09-29 17:56:59

+0

@ user1798797:代碼現在將讀取* all *'Data set'數字,將它們收集到一個列表中。 – 2014-09-29 17:59:00