gpt4 book ai didi

python - 为什么 textwrap.wrap() 和 textwrap.fill() 这么慢?

转载 作者:行者123 更新时间:2023-11-28 19:35:50 25 4
gpt4 key购买 nike

为什么是textwrap.wrap()textwrap.fill()太慢了?例如,在我的笔记本电脑上包装一个 10000 个字符的字符串需要将近两秒半。

$ python -m timeit -n 10 -s 's = "A" * 10000; import textwrap' 'textwrap.fill(s)'
10 loops, best of 3: 2.41 sec per loop

将其与改编自 an answer to a related Stack Overflow question 的代码进行比较

#!/usr/bin/env python
# simplewrap.py
def fill(text, width=70):
return '\n'.join(text[i:i+width] for i in
range(0, len(text), width))

它比 textwrap 快几个数量级:

$ python -m timeit -n 10 -s 's = "A" * 10000; import simplewrap' 'simplewrap.fill(s)'
10 loops, best of 3: 37.2 usec per loop

最佳答案

分析代码表明,时间被用于将输入拆分为单词的正则表达式占用。它的一个精简版本表现出同样的问题是:

import re
s = "A" * 10000
wordsep_re = re.compile(
r'\w+[^\W]-'
)
wordsep_re.split(s)

我相信 Python 使用递归回溯来匹配正则表达式。我认为发生了什么事是 python 一直试图匹配 - 并且失败了,因此不得不备份。

您可以使用:

textwrap.fill(s, break_on_hyphens = False)

您会发现速度非常快。当文本中没有任何空格时,用于匹配连字符的正则表达式会出现病态情况。

关于python - 为什么 textwrap.wrap() 和 textwrap.fill() 这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11781261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com