【问题标题】:python odfpy AttributeError: Text instance has no attribute encodepython odfpy AttributeError:文本实例没有属性编码
【发布时间】:2015-09-24 15:36:17
【问题描述】:

我正在尝试使用 odfpy 模块读取 ods(Opendocument 电子表格)文档。到目前为止,我已经能够提取一些数据,但是每当单元格包含非标准输入时,脚本就会出错:

Traceback (most recent call last):
File "python/test.py", line 26, in <module>
 print x.firstChild
File "/usr/lib/python2.7/site-packages/odf/element.py", line 247, in __str__
 return self.data.encode()
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0105' in position 4: ordinal not in range(128)

我试图强制对输出进行编码,但显然它与 print 不兼容:

Traceback (most recent call last):
  File "python/test.py", line 27, in <module>
   print x.firstChild.encode('utf-8', 'ignore')
AttributeError: Text instance has no attribute 'encode'

这里的问题是什么?如何在不编辑模块代码的情况下解决它(我想不惜一切代价避免)?是否有替代方法可以在输出上运行编码?

这是我的代码:

from odf.opendocument import Spreadsheet
from odf.opendocument import load
from odf.table import Table,TableRow,TableCell
from odf.text import P
import sys,codecs
doc = load(sys.argv[1])
d = doc.spreadsheet
tables = d.getElementsByType(Table)
for table in tables:
  tName = table.attributes[(u'urn:oasis:names:tc:opendocument:xmlns:table:1.0', u'name')]
  print tName
  rows = table.getElementsByType(TableRow)
  for row in rows[:2]:
    cells = row.getElementsByType(TableCell)
    for cell in cells:
      tps = cell.getElementsByType(P)
      if len(tps)>0:
        for x in tps:
          #print x.firstChild
          print x.firstChild.encode('utf-8', 'ignore')

【问题讨论】:

  • 您的实际脚本每个缩进是否只有 2 个空格?它非常难以阅读。
  • 是的,这对我和 python 缩进解析器都不是问题。
  • dir(x.firstChild) 这提供了什么
  • 我相信问题还在继续,在 github 问题中,遇到同样问题的人比有同样问题的人还多。 github.com/eea/odfpy/issues/28

标签: python python-2.7 odf


【解决方案1】:

可能你没有使用最新的odfpy,在最新版本中,Text__str__方法实现为:

def __str__(self):
    return self.data

更新odfpy到最新版本,修改你的代码为:

print x.firstChild.__str__().encode('utf-8', 'ignore')

更新

这是获取Text 的原始unicode 数据的另一种方法:__unicode__。因此,如果您不想更新odfpy,请将您的代码修改为:

print x.firstChild.__unicode__().encode('utf-8', 'ignore')

【讨论】:

  • 后一种使用 unicode 的方法也可以,谢谢。
【解决方案2】:

似乎图书馆本身正在调用encode() -

return self.data.encode()

这使用系统默认编码,在您的情况下似乎是ascii。您可以使用 -

进行检查
import sys
sys.getdefaultencoding()

从追溯来看,实际数据似乎存在于一个名为 data 的变量中。

尝试执行以下操作 -

print x.firstChild.data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多