[英]Python read series of information in text file between two strings
我有一個具有以下格式類型的文本文件:
BEGIN *A information here* END
BEGIN *B information here* END
BEGIN *C information here*
*C additional information here*
*C additional information here*
BEGIN *C secondary information here*
*C additional secondary information*
BEGIN *C tertiary information* END
END
BEGIN *C secondary information*
END
END
BEGIN *D information here* END
我想讀取BEGIN和END之間的信息,並以相同的格式將信息保留為列表列表。 我嘗試用“ [”和“]”分別替換“ BEGIN”和“ END”,然后嘗試評估結果字符串,但是當它在信息中擊中一個數字時,它將引發語法錯誤。 這是我嘗試的代碼:
with open(filepath) as infile:
mylist = []
for line in infile:
line = line.strip()
line = line.replace('BEGIN', '[')
line = line.replace('END', ']')
mylist.append(line)
for n in mylist:
print n
產生:
[ *A information here* ]
[ *B information here* ]
[ *C information here*
*C additional information here*
*C additional information here*
[ *C secondary information here*
*C additional secondary information*
[ *C tertiary information* ]
]
[ *C secondary information*
]
]
[ *D information here* ]
有沒有辦法像這樣將數據作為列表列表取出:
>>>for n in mylist:
>>> print n
[*A information here*]
[*B information here*]
[*C information here* *C additional information here* [*C secondary information here* *C additional secondary information* [*C tertiary information*]] [*C secondary information*]]
[*D information here*]
假設文件不包含任何括號,則可以像以前一樣用括號替換“ BEGIN”和“ END”,然后編寫一個遞歸函數來解析它:
def parse(text):
j=0
result = [""] # initialize a list to store the result
for i in range(len(text)): # iterate over indices of characters
if text[i] == "[":
s = "" # initialize a string to store the text
nestlevel = 1 # initialize a variable to store number of nested blocks
j = i
while nestlevel != 0: # loop until outside all nested blocks
j+=1
# increment or decrement nest level on encountering brackets
if text[j]=="[":
nestlevel+=1
if text[j]=="]":
nestlevel-=1
# data block goes from index i+1 to index j-1
result.append(parse(text[i+1:j])) # slicing doesn't include end bound element
result.append("")
elif i>j:
result[-1]=result[-1]+text[i]
return result
with open(filepath) as f:
data=parse(f.read().replace("BEGIN","[").replace("END","]"))
這只是一個粗略的想法,我相信可以通過其他方式對其進行優化和改進。 另外,它可能會返回空字符串,其中子列表之間沒有文本。
我設法使它與以下代碼一起使用:
def getObjectData(filepath):
with open(filepath) as infile:
mylist = []
linenum = 0
varcount = 0
varlinedic = {}
for line in infile:
line = line.replace('BEGIN', '[').replace('END', ']')
linenum += 1
if line.startswith('['):
varcount += 1
varlinedic[varcount] = linenum
mylist.append(line.strip())
for key in varlinedic:
if key == varlinedic[key]:
print mylist[varlinedic[key]-1:varlinedic[key]]
else:
print mylist[varlinedic[key-1]:varlinedic[key]]
print getObjectData(filepath)
它返回:
['[ *A information here* ]']
['[ *B information here* ]']
['[ *C information here*', '*C additional information here*', '*C additional information here*', '[ *C secondary information here*', '*C additional secondary information*', '[ *C tertiary information* ]', ']', '[ *C secondary information*', ']', ']']
['[ *D information here* ]']
None
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.