【问题标题】:Trying to remove common words from a file试图从文件中删除常用词
【发布时间】:2020-03-22 12:26:41
【问题描述】:

我正在尝试打印文件中最常用单词的列表。但是,我也试图忽略常用词。 我目前已经编写了这段代码

import csv
import collections
from collections import Counter

with open('billboardtop1002015lyrics.txt',encoding='ISO-8859-1') as csv_file:
mostcommonword = []

counter = Counter(csv_file.read().strip().split())

commonwords = (counter.most_common(30))

ignore_words = ['i','you','me','the','that','on','is','when','if','in','dont','for','when']

 if commonwords not in ignore_words:
    mostcommonword.append(commonwords)
    print(mostcommonword)

这不起作用,我得到的输出中包含“我”、“你”等字样。 我对 python 很陌生,这是我从事的第一个项目。

有什么我遗漏的或者更简单的方法来解决这个问题吗?

谢谢!

【问题讨论】:

  • 我相信这可能超出了本网站的范围,定义为here。这当然是一个非常广泛的问题。

标签: python database machine-learning


【解决方案1】:

你应该首先消除被忽略的单词,然后找到最常见的。

import csv
import collections
from collections import Counter

ignore_words = ['i', 'you', 'me', 'the', 'that', 'on', 'is', 'when', 'if', 'in', 'dont', 'for', 'when']

with open('billboardtop1002015lyrics.txt', encoding='ISO-8859-1') as csv_file:
    lyrics = csv_file.read().strip().split()
    lyrics_ignored = [t for t in lyrics if t not in ignore_words]
    counter = Counter(lyrics_ignored)
    mostcommonwords = (counter.most_common(30))
    print(mostcommonwords)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多