我已将此dict
从网络上删除,但它附带了unicode
问题:
{'track': [u'\u201cAnxiety\u201d',
u'\u201cLockjaw\u201d [ft. Kodak Black]',
u'\u201cMelanin Drop\u201d',
u'\u201cDreams\u201d',
u'\u201cIntern\u201d',
u'\u201cYou Don\u2019t Think You Like People Like Me\u201d',
u'\u201cFirst Day Out tha Feds\u201d',
u'\u201cFemale Vampire\u201d',
u'\u201cGirlfriend\u201d',
u'\u201cOpposite House\u201d',
u'\u201cGirls @\u201d [ft. Chance the Rapper]',
u'\u201cI Am a Nightmare\u201d']}
这是使用regex
剥离这些字符的最佳方式,还是有一些decode
方法?
以及如何?
答案 0 :(得分:5)
这些是引号(“和”)。如果你只是想在字符串的开头或结尾摆脱它们,最简单的是strip
它们。
>>> u'\u201cAnxiety\u201d'.strip(u'\u201c\u201d')
u'Anxiety'
如果你想在字符串中的任何地方删除它们,replace
它们:
>>> u'\u201cAnxiety\u201d'.replace(u'\u201c', '').replace(u'\u201d', '')
u'Anxiety'
答案 1 :(得分:0)
dict['track'] = list(map(lambda x: x.replace('\u201c','').replace('\u201d',''), dict['track']))
更好的可读解决方案(在我看来):
dict['track'] = [x.replace(u'\u201c', '').replace(u'\u201d', '') for x in dict['track']]
快速解释:dict['track']
是a
词典中的第一个唯一值,是一个字符串列表,每个字符串都有不必要的u'\u201c'
和u'\u201d'
。
我们在Python中使用list comprehensions来遍历该列表,并且对于该列表中的每个字符串x
将其u'\u201c'
和u'\u201d'
替换为空字符串''
,让它们消失。
如果您的字典中有多个值,或者'track'
以外的其他键,并且想要使这些代码更通用并且适用于具有任何键名的每个字典,我们可以遍历字典中的值,并将上述代码应用于所有字典的值:
for k,v in dict.items():
dict[k] = [x.replace(u'\u201c', '').replace(u'\u201d', '') for x in v]