Python 单词出现次数

Python Word occurrence

我试图打开并阅读一个文本文件并计算一个词出现的类型数,例如,如果文本中出现了 better 这个词,它的出现频率为 8。我附上了下面的代码。我收到以下错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x97 in position 861: invalid start byte

file=open('IntroductoryCS.txt')

wordcount={}

for word in file.read().split():
        if word not in wordcount:
           wordcount[word] = 1
        else:
           wordcount[word] += 1

for k,v in wordcount.items():
      print k, v

我正在使用 IDLE 3.5.1

看来你 IntroductoryCS.txt 不是 UTF-8。

您应该在 open() 函数中更改编码。

像这样:

file=open('IntroductoryCS.txt', encoding='<your_encoding_here>')

参见文档 here

我不知道你的文件是什么编码,但试试这个:

file=open('IntroductoryCS.txt', encoding='latin-1')

这里有可用的encodings

您的代码运行良好。

尝试将 txt 文件另存为 UTF-8。用记事本打开文件,然后另存为,选择编码UTF-8.