【问题标题】:pickling with unicode in Python3在 Python3 中使用 unicode 进行酸洗
【发布时间】:2018-02-02 23:17:29
【问题描述】:

我正在尝试腌制 {word : {docId : int}} 形式的字典。我的代码如下:

def vocabProcess(documents):
    word_splitter = re.compile(r"\w+", re.VERBOSE)
    stemmer=PorterStemmer()#
    stop_words = set(stopwords.words('english'))

    wordDict = {}
    for docId in documents:
        processedDoc = [stemmer.stem(w.lower()) for w in 
        word_splitter.findall(reuters.raw(docId)) if not w in stop_words]

        for w in processedDoc:
            if w not in wordDict:
                wordDict[w] = {docId : processedDoc.count(w)}
            else:
                wordDict[w][docId] = processedDoc.count(w)
    with open("vocabListings.txt", "wb") as f:
        _pickle.dump(wordDict, f)

if __name__ == "__main__":
    documents = reuters.fileids()
    with open("vocabListings.txt", "r") as f:
        vocabulary = _pickle.load(f)    

当我运行这段代码时,我得到了错误

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 2399: 
character maps to <undefined>

当所有路透社文档/文档中没有 unicode 时,为什么会出现这种情况?我该如何解决这个问题,以便我仍然可以使用 _pickle 模块?

【问题讨论】:

    标签: python pickle python-unicode


    【解决方案1】:

    您需要使用二进制模式来编写读取泡菜。你的问题是:

    with open("vocabListings.txt", "r") as f:
        vocabulary = _pickle.load(f)    
    

    在 Python 3 上,以文本模式读取会给出 str(文本类型)而不是 bytespickle 使用的二进制类型)。它会尝试解码数据,就好像它是您的语言环境编码中的文本一样;原始二进制流在许多编码中不太可能有效,因此在pickle 看到数据之前就会出错。

    在 Windows 上的 Python 2 上,有时可以以文本模式读取,除非二进制数据在数据中有 \r\n 序列,在这种情况下,数据将被损坏(它将被替换为 \n 在数据pickle 看到)。

    无论哪种方式,使用模式"rb" 阅读(就像你使用"wb" 写作一样),你会没事的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多