Tôi có một tập tin với rất nhiều phần trong định dạng này:Làm cách nào để lặp qua tệp văn bản này nhanh hơn?
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
Các tập tin có thể được hàng trăm ngàn dòng dài. Số thuộc tính và trường cho mỗi phần có thể khác nhau. Tôi muốn xây dựng một vài từ điển để giữ một số giá trị này. Tôi có một từ điển riêng biệt đã giữ tất cả các giá trị 'thuộc tính' có thể có.
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
Vấn đề của tôi là vòng lặp while để phù hợp với tất cả các giá trị trường đáng chú ý là chậm hơn so với phần còn lại của các mã: 0.5s 2.2s vs theo cProfile nếu tôi loại bỏ các vòng lặp while. Tôi tự hỏi tôi có thể làm gì để tăng tốc độ.
Bạn có thể sử dụng trình tạo biểu thức thông thường - nếu bạn cung cấp một số mẫu thực có thể giúp bạn tốt hơn. – Jan
Tốc độ chậm hơn bao nhiêu? –
@ Tôi không thể cung cấp tệp gốc nhưng tôi sẽ xem liệu tôi có thể tự tạo mẫu không. – Colin