0

我正在尝试使用 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)

我试图在输出上强制编码,但显然它与打印不符:

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')
4

2 回答 2

1

也许你没有使用 latest odfpy,在最新版本中,__str__方法Text实现为:

def __str__(self):
    return self.data

更新odfpy到最新版本,并将您的代码修改为:

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

更新

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

print x.firstChild.__unicode__().encode('utf-8', 'ignore')
于 2015-07-07T09:08:04.957 回答
0

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

return self.data.encode()

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

import sys
sys.getdefaultencoding()

从回溯来看,实际数据似乎存在于一个名为data.

尝试执行以下操作 -

print x.firstChild.data
于 2015-07-07T08:53:50.827 回答