我有 3 个 API,它们将 json 数据返回到 3 个字典变量。我正在从字典中取出一些值来处理它们。我在列表中读取了我想要的具体值valuelist
。步骤之一是删除其中的标点符号。我通常使用string.translate(None, string.punctuation)
对于这个过程,但因为字典数据是 unicode 我收到错误:
wordlist = [s.translate(None, string.punctuation)for s in valuelist]
TypeError: translate() takes exactly one argument (2 given)
有没有解决的办法?通过对 unicode 进行编码或替换string.translate
?
转换方法在 Unicode 对象上的工作方式与在字节字符串对象上的工作方式不同:
>>> help(unicode.translate)
S.translate(table) -> unicode
Return a copy of the string S, where all characters have been mapped
through the given translation table, which must be a mapping of
Unicode ordinals to Unicode ordinals, Unicode strings or None.
Unmapped characters are left untouched. Characters mapped to None
are deleted.
所以你的例子将变成:
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
word_list = [s.translate(remove_punctuation_map) for s in value_list]
但请注意string.punctuation
仅包含 ASCII 标点符号。完整的 Unicode 有更多的标点符号,但这完全取决于您的用例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)