سؤال
ولدي ملف 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 هذا الملف والحصول على وظائف مع نوع وظائفها؟ أيضا، من هذا النص كيف يمكنني تحليل واستخراج. س الاسم؟
وكيف يمكنني الحصول عليها عن طريق العمود إعراب الحكمة وإلا كيف.
وأحتاج إلى مساعدة فورية ... في انتظار حل مناسب كالمعتاد
المحلول
وأعتقد أن هذا قد تكلف أقل من استخدام regexes على الرغم من أنني لست واضحا تماما على ما كنت تحاول إنجاز
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]
وعذرا لكونه الهوس جدا ولكن أنا أحاول الحصول على مؤشر أفضل على خلق comprehensions قائمة وقررت أن هذا هو مستحق في الشباك
نصائح أخرى
for line in open('thefile.txt'):
fields = line.split('|')
if len(fields) < 4: continue
if fields[3].trim() != 'FUNC': continue
dowhateveryouwishwith(line, fields)
وهنا هو النهج الأساسي. ما رأيك؟
# 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])