我正在用 scrapy 解析用西类牙语编写的网页.问题是由于编码错误,我无法保存文本。
这是解析函数:
def parse(self, response):
hxs = HtmlXPathSelector(response)
text = hxs.select('//text()').extract() # Ex: [u' Sustancia mineral, m\xe1s o menos dura y compacta, que no es terrosa ni de aspecto met\xe1lico.']
s = "".join(text)
db = dbf.Dbf("test.dbf", new=True)
db.addField(
("WORD", "C", 25),
("DATA", "M", 15000), # Memo field
)
rec = db.newRecord()
rec["WORD"] = "Stone"
rec["DATA"] = s
rec.store()
db.close()
当我尝试将其保存到 db(a dbf db) 时,出现 ASCII(128) 错误。我尝试使用“utf-8”和“latin1”进行解码/编码,但没有成功。
编辑:
为了保存数据库,我正在使用 dbfpy .我在上面的parse函数中添加了dbf保存代码。
这是错误信息:
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/twisted/internet/base.py", line 1179, in mainLoop
self.runUntilCurrent()
File "/usr/lib/python2.6/dist-packages/twisted/internet/base.py", line 778, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 280, in callback
self._startRunCallbacks(result)
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 354, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/lib/python2.6/dist-packages/twisted/internet/defer.py", line 371, in _runCallbacks
self.result = callback(self.result, *args, **kw)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/rae_spider.py", line 54, in parse
rec.store()
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 211, in store
self.dbf.append(self)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/dbf.py", line 214, in append
record._write()
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 173, in _write
self.dbf.stream.write(self.toString())
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/record.py", line 223, in toString
for (_def, _dat) in izip(self.dbf.header.fields, self.fieldData)
File "/home/katy/Dropbox/proyectos/rae/rae/spiders/fields.py", line 215, in encodeValue
return str(value)[:self.length].ljust(self.length)
exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 18: ordinal not in range(128)
请您参考如下方法:
请不要记住DBF files don't support unicode at all 我还建议使用 Ethan Furman 的 dbf 包(另一个答案中的链接)
您只能使用 'table = dbf.Table('filename') 来猜测真实类型。
使用非 cp437 编码的示例是:
#!/usr/bin/env python
# coding: koi8-r
import dbf
text = 'текст в koi8-r'
table = dbf.Table(':memory:', ['test M'], 128, False, False, True, False, 'dbf', 'koi8-r')
record = table.append()
record.test = text
请注意以下有关版本 0.87.14 和“dbf”表类型的信息:
使用 DBF 包 0.87.14,您可以在“.../site-packages/dbf/tables.py”的第 686 行找到异常“TypeError: ord() excepted character...”
只有 'dbf' 表类型受到此 tupo 的影响!
免责声明:我不知道在以下值中使用真正正确的值,所以不要因为与此“修复”不兼容而责怪我。
您可以在第 490 行和第 491 行将值“”替换为“\0”(至少)以使该测试可行。
