Python - 从键替换特殊字符,字典中的值

Posted

技术标签:

【中文标题】Python - 从键替换特殊字符,字典中的值【英文标题】:Python - Replace Special Characters from key, value in dictonary 【发布时间】:2019-05-20 00:14:25 【问题描述】:

我有这个字典:

dict1='Period': '100.02\xa0minutes[2]', 'Repeat interval': '23\xa0days', 'Epoch': '25 January 2015, 00:45:13\xa0UTC[2]', 'Band': 'S Band(TT&C support)X Band(science data acquisition)', 'Bandwidth': 'up\xa0to\xa0722kbit/s\xa0download\xa0(S Band)up\xa0to\xa018.4Mbit/s\xa0download\xa0(X Band)up\xa0to\xa04kbit\xa0/s\xa0upload\xa0(S Band)'

我想替换所有\xa0 by " " 我试试这个:

clean_dict = key.strip(): item.strip() for key, item in dict1.items()

但是输出是一样的。 我也试试这个:

    new_keys = list(dict1.keys())
    new_values = list(dict1.values())
    new_keys2 = list()
    new_values2 = list()
    for element in new_keys:
        print (element)
        new_keys2.append(element.replace("\xa0", " "))
    for element in new_values:
        print(element)
        new_values2.append(element.replace("\xa0", " "))
    new_dict = dict(zip(new_keys2,new_values2))

但这也给了我相同的输出。我该如何解决这个问题?

【问题讨论】:

***.com/questions/10993612/… 【参考方案1】:

你可以试试replace:

python 3.x

>>> dict2 = k.replace(u'\xa0', ' ') : v.replace(u'\xa0', ' ') for k, v in dict1.items()

python 2.7

>>> dict2 = k.replace(u'\xa0', ' ') : v.replace(u'\xa0', ' ') for k, v in dict1.iteritems()

结果是

>>> print(dict2)
'Band': 'S Band(TT&C support)X Band(science data acquisition)',
 'Bandwidth': 'up to 722kbit/s download (S Band)up to 18.4Mbit/s download (X Band)up to 4kbit /s upload (S Band)',
 'Epoch': '25 January 2015, 00:45:13 UTC[2]',
 'Period': '100.02 minutes[2]',
 'Repeat interval': '23 days'

【讨论】:

【参考方案2】:

试试这个

unicodedata.normalize("NFKD", key): unicodedata.normalize("NFKD", item) for key, item in dict1.items()

输出

 'Repeat interval': '23 days',
 'Epoch': '25 January 2015, 00:45:13 UTC[2]',
 'Band': 'S Band(TT&C support)X Band(science data acquisition)',
 'Bandwidth': 'up to 722kbit/s download (S Band)up to 18.4Mbit/s download (X Band)up to 4kbit /s upload (S Band)'

【讨论】:

以上是关于Python - 从键替换特殊字符,字典中的值的主要内容,如果未能解决你的问题,请参考以下文章

php怎样过滤掉特殊字符啊 ☺

替换字符串python中的特殊字符

替换python字符串中的特殊字母[重复]

python特殊符号的更改,替换

url 中的特殊字符 % # & = ? / + 无法被后端解析问题分析及解决方法

python-参数化-(excel中特殊标识字符替换数据)