我已经编写了我的程序来读取文本文件中的单词,并将它们输入到sqlite数据库中,并将它视为字符串。但我需要输入一些包含日耳曼语的词:äöß。python:打开并读取包含德国变音符号的文件作为unicode
这里是一个准备一块代码:
我TREID都与# - - 编码:ISO-8859-15 - - 和# - - 编码:UTF-8 - - 无差异( !)
# -*- coding: iso-8859-15 -*-
import sqlite3
dbname = 'sampledb.db'
filename ='text.txt'
con = sqlite3.connect(dbname)
cur = con.cursor()
cur.execute('''create table IF NOT EXISTS table1 (id INTEGER PRIMARY KEY,name)''')
#f=open(filename)
#text = f.readlines()
#f.close()
text = u'süß'
print (text)
cur.execute("insert into table1 (id,name) VALUES (NULL,?)",(text,))
con.commit()
sentence = "The name is: %s" %(text,)
print (sentence)
f.close()
con.close()
上面的代码运行良好。但是我需要从包含单词'süß'的文件中读取'文本'。所以,当我取消了3条线(f.open(文件名)......),和评论文本=u'süß”它带来的误差
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
我试着编解码器模块读取一个UTF- 8,iso-8859-15。但我无法将它们解码为字符串'süß',我需要在代码末尾完成我的句子。
在插入数据库之前,我尝试解码为utf-8。它的工作,但我不能用它作为字符串。
有没有一种方法可以从文件导入süß并将其用于插入到sqlite并使用字符串?
更多详细信息:
在这里,我增加更多的细节进行澄清。我以前使用过codecs.open
。 包含单词süß的文本文件保存为utf-8
。使用f=codecs.open(filename, 'r', 'utf-8')
和text=f.read()
,我读取文件为unicode u'\ufeffs\xfc\xdf'
。在sqlite3插入此unicode是顺利完成:cur.execute("insert into table1 (id,name) VALUES (NULL,?)",(text,))
。
的问题是在这里:sentence = "The name is: %s" %(text,)
给人u'The name is: \ufeffs\xfc\xdf'
,我也需要print(text)
作为我的输出苏斯,而print(text)
带来了这个错误UnicodeEncodeError: 'charmap' codec can't encode character u'\ufeff' in position 0: character maps to <undefined>
。
谢谢。
的编码参数*应*有在你的'text'文字中有很大的不同。 –
澄清:模块顶部的编码声明会影响源代码中指定的“text =u'süß''。它对从文件读取的文本有*无效。你可以使用'codecs.open()'作为后者。 – jfs
'readlines'返回一个列表。使用'f.read()。strip()'获取文件的文本为字符串。然后,你可以开始担心编码了。 – alexis