从docx中读取特殊字符

时间:2014-08-06 03:16:01

标签: python utf-8

我正在尝试读取docx文件,而不是将其拆分为重要部分并将其插入到我的数据库中。问题是我的docx文件是葡萄牙语,因此它有很多特殊字符(例如á,ã,â) 我已经努力解决这个问题了好几天了。因为当我添加到数据库时,特殊字符变为'?'。

这是我的代码:

cursor = db.cursor()
document = docx.Document('teste.docx')
docText = '\n\n'.join([paragraph.text.encode('utf-8') for paragraph in document.paragraphs])
d2 = docText.decode("utf-8")

N = len(d2.encode(sys.stdout.encoding, errors='replace').split("\n"))

query = ''
questao = {}

for i in range(0,N):
    s = d2.encode(sys.stdout.encoding, errors='replace').split("\n")[i]
    try:
        isinstance(int(s[0:2]), int)
        questao[num_questoes] = d2.encode(sys.stdout.encoding, errors='replace').split("\n")[i][3:len(s)]
        query = 'INSERT INTO multichoice_question (category_id, content) VALUES ("4", "' + d2.encode(sys.stdout.encoding, errors='replace').split("\n")[i][3:len(s)] + '");'
        try:
            cursor.execute(query)
            db.commit()
        except MySQLdb.Error, e:
            print "error %s" %e
            db.rollback()  
    except:
        pass

1 个答案:

答案 0 :(得分:1)

是MySQL数据库吗?可能只有两个问题:

  1. 创建与数据库的连接时,您忘记将连接字符集设置为utf8,因此它会尝试将您的文本写为ASCI(这在MySQL中是默认的)。显示与数据库建立连接的部分。 如果您使用的是MySQLdb软件包,则必须添加use_unicode = True和charset =" utf8" MySQLdb.connect函数调用的参数。
  2. 你的表/列charset不是UTF8,而是ASCI charset之一。更改。