优化代码import os import re def parse_data(contents): contents = contents.lower() title_start = contents.find('<title>') title_end = contents.find('</title>') title = contents[title_start+len('<title>'):title_end] text_start = contents.find('<text>') text_end = contents.find('</text>') text = contents[text_start+len('<text>'):text_end] return title+" "+text def read_data(path): contents = [] for filename in os.listdir(path): data = parse_data(open(path+'/'+filename, 'r').read()) filename = re.sub(r'\D', "", filename) contents.append((int(filename), data)) return contents
时间: 2023-05-18 18:02:51 浏览: 136
Read data from the Excel spreadsheet.zip_Spreadsheet::Read_excel
可以使用列表推导式和with语句来优化代码,如下所示:
import os
import re
def parse_data(contents):
contents = contents.lower()
title_start = contents.find('<title>')
title_end = contents.find('</title>')
title = contents[title_start + len('<title>'):title_end]
text_start = contents.find('<text>')
text_end = contents.find('</text>')
text = contents[text_start + len('<text>'):text_end]
return title, text
def read_data(path):
contents = [(int(re.sub(r'\D', "", filename)), parse_data(open(os.path.join(path, filename), 'r').read())) for filename in os.listdir(path)]
return contents
这样可以更加简洁和高效地实现相同的功能。
阅读全文