2013-11-24 38 views
2

我需要处理文本,像比较单词与字典一样的词......并且我有编码问题。 txt文件是utf-8,代码也是utf-8。问题是当分裂为字符像š,č,ť,á,...我尝试编码和解码并在网上搜索,但我不知道如何处理它。我看了文件系统编码,它是mbcs,defaultencoding是utf-8。你能帮助我吗?下面的代码是第一个版本。python中的文本编码错误

#!/usr/bin/env python 
    # -*- coding: utf-8 -*- 

    f = open("text.txt", "r+") 

    text = f.read() 

    sentences = re.split("[.!?]\s", text) 

    words = re.split("\s", sentences[0]) 

    print sentences[0] 
    print words 

和结果是:

Nexus 5 patrí v sučasnosti medzi a najlepšie aj smartfóny 

['\xef\xbb\xbfNexus', '5', 'patr\xc3\xad', 'su\xc4\x8dasnosti', 'medzi', 'najlep\xc5\xa1ie', 'smartf\xc3\xb3ny'] 

当我使用:

f = codecs.open("text.txt", "r+", encoding="utf-8") 

结果是:

Nexus 5 patrí v sučasnosti medzi a najlepšie aj smartfóny 

[u'\ufeffNexus', u'5', u'patr\xed', u'su\u010dasnosti', u'medzi', u'najlep\u0161ie', u'smartf\xf3ny'] 

,我需要一个像输出:

['Nexus', '5', 'patrí', 'v', 'súčastnosti',....] 
+0

你在列表中有unicode字符串。如果您不想打印表示,请不要打印列表容器,而是单独打印每个元素。 –

+0

好了,现在我明白了,但是当我想要比较列表中的每个元素与字典来查找匹配时它会正常工作吗? – TheBP

+0

你会使用unicode文字来测试,但是。 –

回答

1

编码处理是正确的,u'patr\xed'只是Python中unicode字符串的表示形式。试试print u'patr\xed'在一个shell中看看你自己。

话虽如此,因为您似乎想将其用作字典,所以使用unidecode模块将unicode字符串规范化为ASCII可能会很有用。

+0

我想将它与distionary进行比较以找到匹配。如何使用Windows安装unicode?只有Linux软件包。 – TheBP

+0

我认为最好的方法是[安装pip](http://stackoverflow.com/questions/4750806/how-to-install-pip-on-windows),然后运行命令'pip install unidecode'。 Unidecode非常适合你想要的东西,你可以用它来将字典中的单词标准化为ASCII,然后你可以对你想查找的单词进行相同的操作,看它是否在你的字典中。 – elias