我有很多部分在這個格式的文件:如何更快地遍歷這個文本文件?
section_name_1 <attribute_1:value> <attribute_2:value> ... <attribute_n:value> {
field_1 finish_num:start_num some_text ;
field_2 finish_num:start_num some_text ;
...
field_n finish_num:start_num some_text;
};
section_name_2 ...
... and so on
該文件可以是幾十萬排長隊的。每個部分的屬性和字段數可以不同。我想建立一些字典來保存這些值。我已經有一個單獨的字典,它包含所有可能的'屬性'值。
import os, re
from collections import defaultdict
def mapFile(myFile, attributeMap_d):
valueMap_d = {}
fieldMap_d = defaultdict(dict)
for attributeName in attributeMap_d:
valueMap_d[attributeName] = {}
count = 0
with open(myFile, "rb") as fh:
for line in fh:
# only look for lines with <
if '<' in line:
# match all attribute:value pairs inside <> brackets
attributeAllMatch = re.findall(r'<(\S+):(\S+)>', line)
attributeAllMatchLen = len(attributeAllMatch)
count = 0
sectionNameMatch = re.match(r'(\S+)\s+<', line)
# store each section name and its associated attribute and value into dict
for attributeName in attributeMap_d:
for element in attributeAllMatch:
if element[0] == attributeName:
valueMap_d[attributeName][sectionNameMatch.group(1).rstrip()] = element[1].rstrip()
count += 1
# stop searching if all attributes in section already matched
if count == attributeAllMatchLen: break
nextLine = next(fh)
#in between each squiggly bracket, store all the field names and start/stop_nums into dict
#this while loop is very slow...
while not "};" in nextLine:
fieldMatch = re.search(r'(\S+)\s+(\d+):(\d+)', nextLine)
if fieldMatch:
fieldMap_d[sectionNameMatch.group(1)][fieldMatch.group(1)] = [fieldMatch.group(2), fieldMatch.group(3)]
nextLine = next(fh)
return valueMap_d
我的問題是,while循環,所有的字段值相匹配是明顯比其餘代碼的要慢0.5秒與2.2S根據CPROFILE如果我刪除了while循環。我想知道我能做些什麼來加速它。
您可以使用帶有正則表達式的生成器 - 如果您提供了一些真實的樣本,則可以更好地幫助您。 – Jan
它慢多少? –
@Jan我無法提供原始文件,但我會看看我是否可以自己創建樣本。 – Colin