记录python字典,其中的值可能有unicode错误

2024-09-25 08:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将详细日志添加到现有脚本中。此脚本通过soap客户机API将数据提取到字典中。我使用日志记录模块和格式函数来记录这个字典。在

在某些情况下,我会得到如下所示的unicode异常,因为一个值可能包含非ascii字符,从而导致异常。在

参考样本:

ref = {'Name': 'John', 'Surname': 'Doe', 'MI': None, 'Title':  u'\xe2\x80\xa2\tEngineer_I'}

'\xe2\x80\xa2\tEngineer_I', is .encode('utf-8') representation of the value returned though below query.

当前代码:

^{pr2}$

错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2022' in position 0: ordinal not in range(128)

回溯

Traceback (most recent call last):
  File "stack.py", line 65, in <module>
    query_db(db_obj)
  File "stack.py", line 50, in query_db
    logger.info("This is the reference data: {}".format(ref))
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2022' in position 0: ordinal not in range(128)

解决方法

为了解决这个问题,我编写了另一个函数,如下所示:

# Dictionary comprehension to encode all unicode values as ascii and ignore errors
def convert_to_str(ref):
    return {k: v.encode('ascii', 'ignore') if v else v for k, v in ref.iteritems()}

有更好的解决办法吗?

这对我有用,但我想知道,有没有更好的方法来处理这个问题? 我可以将任何参数传递给logger或format函数以编码为ascii或忽略unicode错误吗?在

我正在使用python2.7.6


Tags: 函数in脚本refdb字典记录ascii
1条回答
网友
1楼 · 发布于 2024-09-25 08:29:31

可以使用str()将dict转换为字符串,代码如下

logger = logging.getLogger(name)
ref_data = soap_query()
for ref in ref_data:
    logger.debug("This is the reference data: {}".format(str(ref)))

相关问题 更多 >