gpt4 book ai didi

python - 正则表达式删除所有非字母/非数字字符[Python]?

转载 作者:太空宇宙 更新时间:2023-11-03 14:47:55 25 4
gpt4 key购买 nike

我有一本字典:

d = {'<word>':1,'-word':12, 'word':1, '$(*#%&^#&@#':2, '!@**$12word*&':4, '::':10, '1230324':1, '+635':5}

我只想删除所有非字母/非数字字符的条目,即 , . ? ! : ;等等。

我尝试过以下方法

regex = re.compile('[\!\?\.\,\:\;\*\(\)\-\+\<\>]')
regex = re.compile('a-zA-Z0-9_')
regex = re.compile('\\W')
regex = re.compile('[\W_]+') // from [1]

但他们不会返回我想要的结果,即:

new_dict = {'<word>':1,'-word':12, 'word':1, '!@**$word*&':4, '1230324':1, '+635':5}

其中条目 '$(*#%&^#&@#'::已被删除。

此外,我使用此代码删除条目,以防有帮助:

new_dict = {k:dictionary[k] for k in dictionary if re.match(regex, k)}

[1] Stripping everything but alphanumeric chars from a string in Python

最佳答案

您希望将\W 的整个字符串与 ^\W+$ 匹配。

像这样的事情就可以了:

$ cat test.py
import re

pattern = r"^\W+$"

d = {'<word>':1,'-word':12, 'word':1, '$(*#%&^#&@#':2, '!@**$12word*&':4, '::':10, '1230324':1, '+635':5}

for k in d.keys():
matches = re.search(pattern, k)
if (matches):
print 'to remove: ' + k
del d[k]

for k in d.keys():
print k

编辑:问题改变:OP想要一次性创建字典。可以这样做:

new_dict = {k:d[k] for k in d.keys() if not(re.search(pattern,k))}

关于python - 正则表达式删除所有非字母/非数字字符[Python]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46108524/

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