python odfpy AttributeError:文本实例没有属性编码

时间:2015-07-07 08:35:50

标签: python python-2.7 odf

我正在尝试使用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 个答案:

答案 0 :(得分:1)

也许您没有使用最新的odfpy,在最新版本中,__str__的{​​{1}}方法实现为:

Text

def __str__(self): return self.data 更新为最新版本,并将代码修改为:

odfpy

<强>更新

这是获取print x.firstChild.__str__().encode('utf-8', 'ignore') Text的原始unicode数据的另一种方法。因此,如果您不想更新__unicode__,请将代码修改为:

odfpy

答案 1 :(得分:0)

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

return self.data.encode()

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

检查一下
import sys
sys.getdefaultencoding()

从回溯中,似乎实际数据存在于名为data的变量中。

尝试执行以下操作 -

print x.firstChild.data
相关问题