我创建了一个字典(作为Keys,它用utf-8编码单词):
import os.path
import codecs
import pickle
from collections import Counter
wordDict = {}
def pathFilesList():
source='StemmedDataset'
retList = []
for r, d, f in os.walk(source):
for files in f:
retList.append(os.path.join(r, files))
return retList
# Starts to parse a corpus, it counts the frequency of each word and
# the date of the data (the date is the file name.) then saves words
# as keys of dictionary and the tuple of (freq,date) as values of each
# key.
def parsing():
fileList = pathFilesList()
for f in fileList:
date_stamp = f[15:-4]
print "Processing file: " + str(f)
fileWordList = []
fileWordSet = set()
# One word per line, strip space. No empty lines.
fw = codecs.open(f, mode = 'r' , encoding='utf-8')
fileWords = Counter(w for w in fw.read().split())
# For each unique word, count occurance and store in dict.
for stemWord, stemFreq in fileWords.items():
if stemWord not in wordDict:
wordDict[stemWord] = [(date_stamp, stemFreq)]
else:
wordDict[stemWord].append((date_stamp, stemFreq))
# Close file and do next.
fw.close()
if __name__ == "__main__":
# Parse all files and store in wordDict.
parsing()
output = open('data.pkl', 'wb')
print "Dumping wordDict of size {0}".format(len(wordDict))
pickle.dump(wordDict, output)
output.close()
当我解pickle pickle数据,并查询这个字典时,我不能查询字母顺序的单词,即使我确定它们在字典中,它总是返回false,但对于数字查询,它工作得很好。以下是我如何解pickle数据和查询:
pkl_file=codecs.open('data.pkl' , 'rb' )
wd=pickle.load(pkl_file)
pprint.pprint(wd) #to make sure the wd is correct and it has been created
print type(wd) #making sure of the type of data structure
pkl_file.close()
#tried lots of other ways to query like if wd.has_key('some_encoded_word')
value= None
inputList= ['اندیمشک' , '16' , 'درحوزه' ]
for i in inputList :
if i in wd :
value = wd[i]
print value
else:
print 'False'
这是我的输出
pa@pa:~/Desktop$ python unpickle.py
False
[('2000-05-07', 5), ('2000-07-05', 2)]
False
所以我很确定编码的单词有问题
您的问题是您正在使用codecs.open。该函数专门用于打开文本文件并自动将数据解码为Unicode。(作为旁注,你通常想要。打开,而不是编解码器。打开,即使在这种情况下。)
打开二进制文件,以字节形式传递给pickle之类的东西。加载时,只需使用内置的open函数,而不是codec .open.
同时,在整个程序中使用Unicode字符串通常会使事情变得更简单,并且只在边缘使用字节字符串,在得到输入时立即解码,并在尽可能晚的时候编码输出。
另外,在非Unicode字符串文本中有Unicode字符。永远,永远,永远不要这样做。这是创建不可见的莫吉贝克字符串的最可靠的方法。当您有非ascii字符时,始终使用Unicode字面值(如u'abc'而不是'abc')。
另外,如果您在源代码中使用非ascii字符,请始终使用编码声明(当然要确保您的编辑器使用与您在编码声明中使用的编码相同),
另外,请记住==(和字典查找)可能无法实现您想要的Unicode。如果您在NFC中存储了一个单词,并在NFD中查找相同的单词,即使它们表示相同的字符串,字符也不会相同。如果不知道你正在使用的确切字符串以及它们是如何表示的,很难知道这在你的代码中是否有问题,但这很常见,例如,Mac程序从文件名中获取字符串或Cocoa GUI应用程序。