面试题答案
一键面试可能的性能瓶颈点
- 内存占用:10GB的海量文本数据一次性读入内存,可能导致内存不足。
- 匹配算法:
re.findall
默认的匹配算法在处理大量数据时效率不高。 - 编码转换:频繁的文本编码转换操作会消耗额外的时间。
优化方案
- 分块读取:将文本数据按块读取,而不是一次性读入内存。
- 使用更高效的正则引擎:例如
regex
库,它对某些复杂正则匹配更高效。
优化后的代码示例
分块读取优化
import re
def findall_by_chunk(pattern, file_path, chunk_size=1024 * 1024):
results = []
with open(file_path, 'r', encoding='utf - 8') as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
matches = re.findall(pattern, chunk)
results.extend(matches)
return results
使用regex
库优化
import regex
def findall_with_regex(pattern, file_path):
with open(file_path, 'r', encoding='utf - 8') as f:
text = f.read()
return regex.findall(pattern, text)
性能对比测试代码
import time
import re
import regex
pattern = r'.'
file_path = 'large_text_file.txt'
# 原re.findall方法
start_time = time.time()
with open(file_path, 'r', encoding='utf - 8') as f:
text = f.read()
original_result = re.findall(pattern, text)
original_time = time.time() - start_time
# 分块读取优化方法
start_time = time.time()
chunk_result = findall_by_chunk(pattern, file_path)
chunk_time = time.time() - start_time
# 使用regex库优化方法
start_time = time.time()
regex_result = findall_with_regex(pattern, file_path)
regex_time = time.time() - start_time
print(f"原re.findall方法耗时: {original_time} 秒")
print(f"分块读取优化方法耗时: {chunk_time} 秒")
print(f"使用regex库优化方法耗时: {regex_time} 秒")
在实际应用中,可根据文本数据的具体特点和需求选择合适的优化方案。同时,在处理文本编码问题时,要确保文件打开和处理时指定正确的编码格式,如'utf - 8'
,以避免乱码等问题。