Skip to main content
 首页 » 编程设计

python之从 NLTK 中读取古腾堡文本

2025年02月15日12shanyou

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

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'] 

您还需要修复字数统计中的缩进,但除此之外它对您有用。