gpt4 book ai didi

python - 从 Most Simply 中清理 A String

转载 作者:行者123 更新时间:2023-11-28 19:32:37 26 4
gpt4 key购买 nike

什么是清理用户输入的字符串的简短方法。这是我在清理困惑时所依赖的代码。如果可以使用更短更智能的版本,那就太好了。

invalid = ['#','@','$','$','%','^','&','*','(',')','-','+','!',' ']
for c in invalid:
if len(line)>0: line=line.replace(c,'')

PS 如何将这个 for(带有嵌套 if)函数放到一行中?

最佳答案

最快的方法是使用 str.translate:

>>> invalid = ['#','@','$','$','%','^','&','*','(',')','-','+','!',' ']
>>> s = '@#$%^&*fdsfs#$%^&*FGHGJ'
>>> s.translate(None, ''.join(invalid))
'fdsfsFGHGJ'

时间比较:

>>> s = '@#$%^&*fdsfs#$%^&*FGHGJ'*100

>>> %timeit re.sub('[#@$%^&*()-+!]', '', s)
1000 loops, best of 3: 766 µs per loop

>>> %timeit re.sub('[#@$%^&*()-+!]+', '', s)
1000 loops, best of 3: 215 µs per loop

>>> %timeit "".join(c for c in s if c not in invalid)
100 loops, best of 3: 1.29 ms per loop

>>> %timeit re.sub(invalid_re, '', s)
1000 loops, best of 3: 718 µs per loop

>>> %timeit s.translate(None, ''.join(invalid)) #Winner
10000 loops, best of 3: 17 µs per loop

在 Python3 上你需要做这样的事情:

>>> trans_tab = {ord(x):None for x in invalid}
>>> s.translate(trans_tab)
'fdsfsFGHGJ'

关于python - 从 Most Simply 中清理 A String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21442672/

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