gpt4 book ai didi

python - string.translate() 与 python 中的 unicode 数据

转载 作者:IT老高 更新时间:2023-10-28 20:25:50 24 4
gpt4 key购买 nike

我有 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?

最佳答案

translate 方法在 Unicode 对象上的工作方式与在字节字符串对象上的工作方式不同:

>>> help(unicode.translate)S.translate(table) -> unicodeReturn a copy of the string S, where all characters have been mappedthrough the given translation table, which must be a mapping ofUnicode ordinals to Unicode ordinals, Unicode strings or None.Unmapped characters are left untouched. Characters mapped to Noneare deleted.

So your example would become:

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 有更多的标点字符,但这完全取决于您的用例。

关于python - string.translate() 与 python 中的 unicode 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11692199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com