gpt4 book ai didi

python - 使 python 循环更快

转载 作者:行者123 更新时间:2023-12-01 09:27:41 25 4
gpt4 key购买 nike

这个小例程可以做得更快吗?使用 elif 会使理解失控,但也许我没有以正确的方式尝试。

def cleanup(s):
strng = ''
good = ['\t', '\r', '\n']
for char in s:
if unicodedata.category(char)[0]!="C":
strng += char
elif char in good:
strng += char
elif char not in good:
strng += ' '
return strng

最佳答案

如果我正确理解您的任务,您希望将所有 unicode 控制字符 替换为空格 除了 \t\n \r

以下是如何使用正则表达式而不是循环更有效地完成此操作。

import re

# make a string of all unicode control characters
# EXCEPT \t - chr(9), \n - chr(10) and \r - chr(13)
control_chars = ''.join(map(unichr, range(0,9) + \
range(11,13) + \
range(14,32) + \
range(127,160)))

# build your regular expression
cc_regex = re.compile('[%s]' % re.escape(control_chars))

def cleanup(s):
# substitute all control characters in the regex
# with spaces and return the new string
return cc_regex.sub(' ', s)

您可以通过操作组成 control_chars 变量的范围来控制要包含或排除的字符。引用List of Unicode characters .

编辑:计时结果。

出于好奇,我进行了一些计时测试,看看当前三种方法中哪一种最快。

我创建了三个名为 cleanup_op(s) 的方法,它们是 OP 代码的副本; cleanup_loop(s) 这是 Cristian Ciupitu 的答案; cleanup_regex(s) 这是我的代码。

这是我运行的内容:

from timeit import default_timer as timer

sample = u"this is a string with some characters and \n new lines and \t tabs and \v and other stuff"*1000

start = timer();cleanup_op(sample);end = timer();print end-start
start = timer();cleanup_loop(sample);end = timer();print end-start
start = timer();cleanup_regex(sample);end = timer();print end-start

结果:

cleanup_op 在大约 1.1 秒内完成

cleanup_loop 在大约 0.02 秒内完成

cleanup_regex 在大约 0.004 秒内完成

因此,任何一个答案都是对原始代码的重大改进。我认为@CristianCiupitu 给出了一个更优雅和Pythonic 的答案,而正则表达式仍然更快。

关于python - 使 python 循环更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235071/

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