解析 .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
我该如何解析这个文件,找到类型为FUNC的函数呢?另外,我怎么从这个文本中提取出.o文件的名字?
我想知道怎么按列来解析它,或者还有其他什么方法。
我需要立即的帮助……像往常一样,期待一个合适的解决方案。
3 个回答
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])
9
for line in open('thefile.txt'):
fields = line.split('|')
if len(fields) < 4: continue
if fields[3].trim() != 'FUNC': continue
dowhateveryouwishwith(line, fields)
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。
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={}
然后如果你想要 Func 类型,你可以使用以下代码:
funcDict={}
for record in fullDict:
if fullDict[record]['Type']=='FUNC':
funcDict[record]=fullDict[record]
抱歉我这么执着,但我想更好地掌握列表推导式的创建,所以我觉得这个值得一试。