簡體   English   中英

UnicodeDecodeError: &#39;charmap&#39; 編解碼器無法解碼位置 295 中的字節 0x9d:字符映射到<undefined>

[英]UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 295: character maps to <undefined>

我正在嘗試從書中運行這個程序。 我創建了名為“alice_2.txt”的文件

def count_words(filename):
    """Count the approximate number of words in a file."""
    try:
        with open(filename) as f_obj: 
            contents = f_obj.read()
    except FileNotFoundError:
        msg = "Sorry, the file " + filename + " does not exist."
        print(msg)
    else:
        # Count approximate number of words in the file.
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) +
            " words.")
            
filename = 'alice_2.txt'
count_words(filename)

但我不斷收到此錯誤消息

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

任何人都可以解釋這意味着什么,以及如何解決它?

您正在嘗試使用無法存儲文件中字符的編碼。 例如ɛ不能在 ascii 中打開,因為它沒有有效的 ascii 代碼。

嘗試使用utf-8打開文件。

with open(filename, encoding='utf8') as f_obj:
    pass
    # DO your stuff

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM