【问题标题】:Remove punctation from every value in Python dictionary从 Python 字典中的每个值中删除标点符号
【发布时间】:2021-02-04 04:48:51
【问题描述】:

我有一本长字典,看起来像这样:

name = 'Barack.'
name_last = 'Obama!'
street_name = "President Streeet?"

list_of_slot_names = {'name':name, 'name_last':name_last, 'street_name':street_name}

我想删除每个插槽的标点(名称、名称_last、...)。

我可以这样做:

name = name.translate(str.maketrans('', '', string.punctuation))
name_last = name_last.translate(str.maketrans('', '', string.punctuation))
street_name = street_name.translate(str.maketrans('', '', string.punctuation))

你知道更短(更紧凑)的写法吗?

结果:

>>> print(name, name_last, street_name)
>>> Barack Obama President Streeet

【问题讨论】:

  • list_of_slot_names 是一个令人困惑的 dict 名称,请考虑 dict_of_slot_names

标签: python string loops dictionary punctuation


【解决方案1】:

使用循环/字典理解

{k: v.translate(str.maketrans('', '', string.punctuation)) for k, v in list_of_slot_names.items()}

如果您想覆盖现有值或分配给新变量,您可以将其分配回list_of_slot_names

您也可以通过以下方式打印

print(*list_of_slot_names.values())

【讨论】:

    【解决方案2】:
    name = 'Barack.'
    name_last = 'Obama!'
    empty_slot = None
    street_name = "President Streeet?"
    
    print([str_.strip('.?!') for str_ in (name, name_last, empty_slot, street_name) if str_ is not None])
    
    -> Barack Obama President Streeet
    

    除非您还想从中间删除它们。然后这样做

    import re
    
    name = 'Barack.'
    name_last = 'Obama!'
    empty_slot = None
    street_name = "President Streeet?"
    
    print([re.sub('[.?!]+',"",str_) for str_ in (name, name_last, empty_slot, street_name) if str_ is not None])
    

    【讨论】:

    • 如何处理像house_number = None这样的空槽?
    • @PParker 你的意思是这样吗?
    • 只要意识到我有一个像birthday = '12.12.1974' 这样的插槽,它会更改为12121974。是否可以仅在字符串末尾删除标点符号?
    • @PParker 是的,这是我回答的第一部分。从技术上讲,第一部分左右删除它。如果您只想在正确的位置删除它,请使用 rstrip 而不是 strip
    【解决方案3】:
    import re, string
    
    s = 'hell:o? wor!d.'
    
    clean = re.sub(rf"[{string.punctuation}]", "", s)
    
    print(clean)
    

    输出

    hello world
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多