【问题标题】:How to remove punctuations in a dictionary如何删除字典中的标点符号
【发布时间】:2018-10-21 03:48:51
【问题描述】:

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

>>> 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)...之后再次定义字典吗?

【问题讨论】:

  • word = word.strip(rpunct) 之后添加一个打印语句print(data[k]),看看会发生什么。问题是您正在尝试在循环中修改列表。如果你用谷歌搜索,你会发现很多问题和解决方法。

标签: string python-3.x punctuation


【解决方案1】:

您实际上并没有修改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}

【讨论】:

  • 嗨,我收到了。 AttributeError: 'dict' 对象没有属性 'append'
  • @song0089 是的,很抱歉。我编辑了代码,因为我试图在字典上调用append(),而不是在值上,这是一个列表。它现在应该可以工作了。
  • 你能帮我完成第二部分吗?我尝试使用您的逻辑来删除列表中的单词,但我没有得到结果stackoverflow.com/questions/52912483/…
【解决方案2】:

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

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

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

import re

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多