我有一个包含一些波斯语文本的文本文件,我想读取该文件并计算每个单词出现的次数,然后打印计算值。这是我的代码:
f = open('C:/python programs/hafez.txt')
wordDict ={}
for line in f:
wordList = line.strip().split(' ')
for word in wordList:
if word not in wordDict:
wordDict[word] = 1
else: wordDict[word] = wordDict[word]+1
print((str(wordDict)))
它产生的结果编码格式错误,我尝试了各种方法来解决这个问题,但没有很好的结果!以下是此代码生成的部分文本:
{"\x00'\x063\x06(\x06": 3, "\x00,\x06'\x06E\x06G\x06": 16, "\x00'\x063\x06*\x06E\x06'\x069\x06": 1, '\x00-\x064\x061\x06': 1, .....}
请您参考如下方法:
有几种方法可以解决这个问题,但也许最简单的方法是使用 codecs.open()。 (我假设您使用 Python 2.7 来使用 Counter 和 with 实现其他一些技巧)。
import codecs
from collections import Counter
wordDict = Counter()
with codecs.open('C:/python programs/hafez.txt','r',encoding='cp720') as f:
for line in f:
wordDict.update(line.strip().split())
for word, count in wordDict.most_common():
print word, count
在Python 3中,你需要用print括号(它在Python 3中是一个函数,但在Python 2中是一个语句),你不需要导入codecs 因为内置的 open() 支持不同的编码。
如果您的编码不是代码页 720,则您需要将该选项替换为相应编码的缩写。
这是了解编码的好机会。虽然我同意乔尔的观点,that no programmer should pretend that we live in a US English / ASCII world ,当您定期处理非拉丁字母表时,编码问题变得尤为重要。 (此外,ASCII 对于英语来说甚至不够——许多英语单词是借来的,保留了它们的重音,以及其他问题。)好的起点是 Joel 的文章(The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)),Pragmatic Unicode。 (包括 Unicode sandwich ),为了便于在 Python 2 中生成上述三明治, codecs模块。还有一个 HOWTO在 Python 文档中,阅读其他文章后更容易理解。
如果您决定使用完整的 Python 3,那么您可以从文档页面顶部的列表框中简单地选择您的确切版本。 BDFL 的 summary of the differences between Python 2 and 3还包括一些关于 Unicode 和 how it's handled differently in Python 2 and 3 的问题.
