1

我正在为 Python 中的字符编码而苦苦挣扎。我有一个脚本,该脚本从充满特殊语言字符的网站获取文章,并且我正在打开一个带有常用单词的外部文件,该txt文件保存到该文件中utf-8并且还包含带有特殊字符的单词。我想设置编码的部分代码如下所示:

def getArticleText(webtext):
articletext = ""
soup = BeautifulSoup(webtext)
for tag in soup.find_all("div", {"class":"dr_article"}):
    for element in tag.find_all("p"):
        articletext += element.contents[0]
    return articletext

def getArticle(url):
htmltext = gethtml.getHtmlText(url)
return getArticleText(htmltext)

def getKeywords(articletext):
common = open("word_rank/comon.txt").read().split('\n')
word_dict = {}
word_list = articletext.lower().split()
for word in word_list:
    if word not in common :
        if word not in word_dict:
            word_dict[word] = 1
        if word in word_dict:
            word_dict[word] += 1
print sorted(word_dict.items(),key=lambda(k,v):(v,k),reverse=True)

现在我对整个打印没有问题articletext。它以正确的方式打印出这些特殊字符。

我的问题是定义中getKeywords定义的关键字,它们以这种方式打印出来,例如:

(u'\u0161elteru', 2), (u'\u010ditateljice', 2),
(u'\u017eeli,', 2), (u'\u0161tekat', 2),

等等...

如何设置该关键字的编码,以便它以正确的方式显示单词?

4

2 回答 2

1

使用单解码

示例用法:

t = u"\u5317\u4EB0"
unidecode( '%s' % (t,) )
于 2013-08-01T12:44:47.087 回答
0

我已经设置好了,.decode('utf-8')它工作了。正是我需要的:D。无论如何,谢谢你们!common = open("word_rank/comon.txt").read().split('\n').read()

于 2013-08-01T12:50:18.613 回答