2009-05-04 105 views
1

我有這樣一個.txt文件:解析.txt文件

Symbols from __ctype_tab.o: 

Name     Value Class  Type   Size  Line Section 

__ctype    |00000000| D |  OBJECT |00000004|  |.data 
__ctype_tab   |00000000| r |  OBJECT |00000101|  |.rodata 


Symbols from _ashldi3.o: 

Name     Value Class  Type   Size  Line Section 

__ashldi3   |00000000| T |  FUNC  |00000050|  |.text 

我怎樣才能parsr這個文件,並與類型FUNC得到的功能呢? 另外,從這個TXT我如何解析和提取.o名稱?

我怎樣才能得到他們通過明智的解析或否則如何。

我需要立即幫助...等待像往常一樣

回答

4

我覺得我雖然不是你所要完成

symbolList=[] 
for line in open('datafile.txt','r'): 
if '.o' in line: 
    tempname=line.split()[-1][0:-2] 
      pass 

if 'FUNC' not in line: 
    pass 

else: 
    symbolList.append((tempname,line.split('|')[0])) 

我已經從其他崗位瞭解到它是便宜什麼完全清楚,這可能花費比使用正則表達式的少並且在第一次閱讀文件時更好地包裝所有數據。因此,如果你想包了整個數據文件在一通,然後你可以做以下代替

fullDict={} 
for line in open('datafile.txt','r'): 
    if '.o' in line: 
     tempname=line.split()[-1][0:-2] 
    if '|' not in line: 
     pass 
    else: 
     tempDict={} 
      dataList=[dataItem.strip() for dataItem in line.strip().split('|')] 
      name=dataList[0].strip() 
      tempDict['Value']=dataList[1] 
      tempDict['Class']=dataList[2] 
      tempDict['Type']=dataList[3] 
      tempDict['Size']=dataList[4] 
      tempDict['Line']=dataList[5] 
      tempDict['Section']=dataList[6] 
      tempDict['o.name']=tempname 
      fullDict[name]=tempDict 
      tempDict={} 

然後,如果你想要的函數功能類型,你可以使用如下:

funcDict={} 
for record in fullDict: 
    if fullDict[record]['Type']=='FUNC': 
     funcDict[record]=fullDict[record] 

對不起,我是如此癡迷,但我試圖更好地處理創建列表解析的問題,並且我決定這是值得的拍攝

2

一個合適的解決方案這是一個基本的方法。你怎麼看?

# Suppose you have filename "thefile.txt" 
import re 

obj = '' 
for line in file('thefile.txt'): 
    # Checking for the .o file 
    match = re.search('Symbols from (.*):', line) 
    if match: 
     obj = match.groups()[0] 

    # Checking for the symbols. 
    if re.search('|', line): 
     columns = [x.strip() for x in a.split('|')] 
     if columns[3] == 'FUNC': 
      print 'File %s has a FUNC named %s' % (obj, columns[0]) 
+0

如果給出文本逐字逐句,您將得到一個IndexError(索引超出範圍) 。 – hbw 2009-05-04 06:09:50

+0

哎呀,好點。我認爲新版本不會有,因爲它只在有|時纔會分裂字符在行中。 – JasonSmith 2009-05-04 06:14:40

+0

+1用於提取.o名稱 – 2009-05-05 01:26:14

8
for line in open('thefile.txt'): 
    fields = line.split('|') 
    if len(fields) < 4: continue 
    if fields[3].trim() != 'FUNC': continue 
    dowhateveryouwishwith(line, fields)