2013-04-16 103 views
0

我是新來正則表達式和python: 我有一個數據存儲在日誌文件,我需要使用正則表達式提取。以下是格式:正則表達式從python表中提取數據

#bytes #repetitions t_min[usec] t_max[usec] t_avg[usec] 
    0   1000   0.01   0.03   0.02 
    4   1000  177.69  177.88  177.79 
    8   1000  175.90  176.07  176.01 
    16   1000  181.51  181.73  181.60 
    32   1000  199.64  199.81  199.72 
    64   1000  228.10  228.27  228.19 
    28   1000  278.70  278.90  278.75 
    256   1000  388.26  388.49  388.39 
    512   1000  593.49  593.82  593.63 
    1024   1000  1044.27  1044.90  1044.59 
+2

什麼是期望的輸出?你試過什麼了? – perreal

+0

這個文件是如何格式化的?標籤分離? (CSV)? – jamylak

+1

http://docs.python.org/2/library/csv.html – user2264587

回答

3

您可以使用split或正則表達式來獲取特定列。分裂是這種情況吸塵器:

import re 
with open("input") as input_file: 
    for line in input_file: 
     # using split to get the 4th column 
     print line.split()[3] 
     # using regex to get the 4th column 
     print re.match(r'^\s*(?:[^\s]+[\s]+){3}([^\s]+)', line).group(1) 
0

如果你需要使用正則表達式,那麼這個腳本做的伎倆:

import re 

number_pattern = '(\d+(?:\.\d+)?)' 
line_pattern = '^\s+%s\s+$' % ('\s+'.join([number_pattern for x in range(5)])) 

f = open('data', 'r') 
for line in f: 
    match = re.match(line_pattern, line) 
    if match is not None: 
    print match.groups() 
0

你只需要(\ S +)

import re 
pattern=re.compile('(\S+)') 
f=open('data.txt', 'r') 
for l in f.readlines(): 
    print pattern.findall(l) 

你也可以做另一種方式

import re 
whitespace=re.compile('\s+') 
    f=open('data.txt', 'r') 
    for l in f.readlines(): 
     print whitespace.split(l.strip()) 
0

喲ü可以使用genfromtxt功能從numpy代替:

>>> import numpy as np 
>>> a = np.genfromtxt("yourlogfile.dat",skip_header=1) 

a將所有數據的數組。