【发布时间】:2010-05-06 05:44:37
【问题描述】:
我有一个如下的姓名和地址文件(示例行)
OSCAR ,CANNONS ,8 ,STIEGLITZ CIRCUIT
我想将它读入名称和值的字典。这里 self.field_list 是文件中固定字段的名称、长度和起点的列表。有什么方法可以加快这种方法? (python 2.6)
def line_to_dictionary(self, file_line,rec_num):
file_line = file_line.lower() # Make it all lowercase
return_rec = {} # Return record as a dictionary
for (field_start, field_length, field_name) in self.field_list:
field_data = file_line[field_start:field_start+field_length]
if self.strip_fields == True: # Strip off white spaces first
field_data = field_data.strip()
if field_data != '': # Only add non-empty fields to dictionary
return_rec[field_name] = field_data
# Set hidden fields
#
return_rec['_rec_num_'] = rec_num
return_rec['_dataset_name_'] = self.name
return return_rec
【问题讨论】:
-
你不能像普通的 csv 文件一样处理它吗?也许在值上运行 strip() 。在撰写本文时这些值是固定长度是否重要?
-
我已经阅读了我得到改进的代码,看起来固定长度字段重叠,所以例如你有 (name:start:length) fname:1:10 和fname_initial:1:1 我很沮丧!
标签: python file dictionary performance