MST

星途 面试题库

面试题:Python正则匹配任意单个字符的性能优化与边界情况

在处理海量文本数据(假设文本数据大小为10GB)时,使用Python正则匹配任意单个字符(包括换行符),现有re.findall方法实现的代码在性能上出现瓶颈。请分析可能的性能瓶颈点,并提出至少两种优化方案,同时考虑边界情况,如文本编码问题,给出优化后的代码示例以及性能对比测试代码。
17.8万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

可能的性能瓶颈点

  1. 内存占用:10GB的海量文本数据一次性读入内存,可能导致内存不足。
  2. 匹配算法re.findall默认的匹配算法在处理大量数据时效率不高。
  3. 编码转换:频繁的文本编码转换操作会消耗额外的时间。

优化方案

  1. 分块读取:将文本数据按块读取,而不是一次性读入内存。
  2. 使用更高效的正则引擎:例如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',以避免乱码等问题。