如何去掉字典中的标点符号

How to remove punctuations in a dictionary

我有一本字典,其中键是字符串,值是字符串列表。我尝试使用 import strings 模块中的 strings.punctuations 删除标点符号。

>>> dat = {'2008':['what!','@cool','#fog','@dddong'],'2010':['hey','@cute']}
>>> 

>>> def remove_punct(data):
...     import string
...     punct = string.punctuation
...     rpunct = punct.replace('@',"") # withold @
...     for k,v in data.items():
...         for word in data[k]:
...             word = word.strip(rpunct)
...     return data
... 
>>> remove_punct(dat)
{'2008': ['what!', '@cool', '#fog', '@dddong'], '2010': ['hey', '@cute']}

为什么我用 # 和 ! 得不到结果?移除了吗?

word.strip(rpunct)...之后,我是否必须再次定义字典?

我使用了不同的正则表达式替换来删除标点符号。

  • \w 将匹配字母数字字符和下划线
  • [^\w] 将匹配任何非字母数字或下划线的内容

你甚至不需要将它包装在一个函数中,你可以使用下面的代码直接更新字典:

import re

for key in dat.keys():
    dat[key] = [re.sub(r'[^\w]', ' ', i) for i in dat[key]]

您实际上并没有在修改 data。您需要直接修改 data 或创建一个新字典并用新数据填充它:

>>> dat = {'2008':['what!','@cool','#fog','@dddong'],'2010':['hey','@cute']}
>>> 
>>> def remove_punct(data):
...     import string
...     new_data = {} # the data we will return
...     punct = string.punctuation
...     rpunct = punct.replace('@',"") # withold @
...     for k,v in data.items():
...         new_data[k] = []
...         for word in data[k]:
...             new_data[k].append(word.strip(rpunct))
...     return new_data
... 
>>> remove_punct(dat)
{'2008': ['what', '@cool', 'fog', '@dddong'], '2010': ['hey', '@cute']}

或更少的行:

>>> from string import punctuation
>>> rpunct = punctuation.replace('@',"") # withold @
>>> new_data = {k: [word.strip(rpunct) for word in dat[k]] for k in dat}