我有很多部分在这个格式的文件:如何更快地遍历这个文本文件?
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