从 NLTK 中读取古腾堡文本

Read in gutenberg text from NLTK

我正在使用以下方法,但它总是抛出无效文件错误:

import nltk

然后

file=open(nltk.corpus.gutenberg.words('austen-persuasion.txt'),"r").read().split().lower()
wordcount={}

for word in file:
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
print ("The frequency of each word in the text file is as follows :")
for k,v in wordcount.items():
    print (k, v)

错误如下

TypeError                                 Traceback (most recent call last)
<ipython-input-88-de499228f7ab> in <module>()
  1 import nltk
----> 2 file=open(nltk.corpus.gutenberg.words('austen-persuasion.txt'),'r').read().split()
  3 #file = nltk.corpus.gutenberg.words('austen-persuasion.txt')
  4 wordcount={}
  5 

TypeError: invalid file: ['[', 'Persuasion', 'by', 'Jane', 'Austen', '1818', ...]

正如@patito 在评论中提到的,你不需要使用 read 也不需要使用 split,因为 nltk 正在将其作为列表读取字。你可以自己看看:

>>> file = nltk.corpus.gutenberg.words('austen-persuasion.txt')
>>> file[0:10]
[u'[', u'Persuasion', u'by', u'Jane', u'Austen', u'1818', u']', u'Chapter', u'1', u'Sir']

您还需要修复字数统计中的缩进,否则它会为您工作。