我有一个实例,我想获取它的 Unicode 表示形式。 Unicode 函数 Unicode() 只接受字符串或缓冲区,所以如果我直接传递实例会出错。
我试过这个:
document = self.grammar.application.ActiveDocument
style_map = [( unicode(s, 'utf-8'), s) for s in document.Styles]
self.styles.set(dict(style_map))
我收到这个错误:
style_map = [( unicode(s, 'utf-8'), s) for s in document.Styles]
TypeError: coercing to Unicode: need string or buffer, instance found
我想知道如何将这些实例转换为 Unicode 字符串表示形式。 我没有实现这些对象。我通过 COM 接口(interface)访问它们。
上下文:
这是一段代码,用于通过 COM 接口(interface)使用 Python 访问 Word 文档中的可用格式样式。 如果我只是尝试将对象转换为 ASCII 字符串,则会出现以下错误:
style_map = [( unicode(s), s) for s in document.Styles]
File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 207, in __str__ return str(self.__call__())
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 3: ordinal not in range(128)
我宁愿在我的代码上处理问题,也不愿修改一些 Win32 代码。 如您所见,我使用的是 Python 2.6。
请您参考如下方法:
尝试使用 repr() 将实例转换为表示:
document = self.grammar.application.ActiveDocument
style_map = [( unicode(repr(s), 'utf-8'), s) for s in document.Styles]
self.styles.set(dict(style_map))
