【问题标题】:Remove words and print most common in PythonPython中最常见的删除单词和打印
【发布时间】:2020-08-21 22:40:02
【问题描述】:

我正在使用 Python Counternltk。我正在尝试搜索外部文档上的单词,用stopwrods 删除一些单词,然后显示最常见的单词。但是出现了一个不知道怎么解决的错误:

AttributeError: 'Counter' object has no attribute 'write'

知道怎么继续吗?

from collections import Counter
import io
from nltk.corpus import stopwords
import nltk
nltk.download('stopwords')
from nltk.tokenize import word_tokenize
#word_tokenize accepts a string as an input, not a file.
stop_words = set(stopwords.words('spanish'))
file1 = open("labs.txt")
line = file1.read()# Use this to read file content as a stream:
words = line.split()
for r in words:
    if not r in stop_words:
        with open("labs.txt") as input_file:
            vonCount = Counter(word for line in input_file for word in line.split())
            vonCount.write(" "+r)
            print(vonCount.most_common(70))

【问题讨论】:

  • 摆脱vonCount.write(" "+r)这一行

标签: python nltk counter


【解决方案1】:

提前知道了。

from collections import Counter
import io
from nltk.corpus import stopwords
import nltk
nltk.download('stopwords')
from nltk.tokenize import word_tokenize
#word_tokenize accepts a string as an input, not a file.
stop_words = set(stopwords.words('spanish'))
file1 = open("labs.txt")
line = file1.read()# Use this to read file content as a stream:
words = line.split()
for r in words:
    if not r in stop_words:
        appendFile = open('cambio.txt','a')
        appendFile.write(" "+r)
        appendFile.close()
        
with open("cambio.txt") as input_file:
    vonCount = Counter(word for line in input_file for word in line.split())
    print(vonCount.most_common(7))

【讨论】:

    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 2020-12-30
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多