【问题标题】:How to append stopwords from being in a text file without using nltk?如何在不使用 nltk 的情况下将停用词附加到文本文件中?
【发布时间】:2023-01-26 10:52:01
【问题描述】:
import re 

input_file = open('documents.txt', 'r')
stopwords = open('stopwords.txt', 'r')

word_count = {}
for line in input_file.readlines():
    words = line.strip()
    words = re.findall('\w+', line)
    for word in words: 
      word = word.lower()
      if not word in word_count: 
        word_count[word] = 1
      else: 
        word_count[word] = word_count[word] + 1

word_index = sorted(word_count.keys())
for word in word_index:
  print (word, word_count[word]) 

目前,这段代码输出一个词在 input_files 文本文档中出现的频率。

但是,我需要省略在 stopwords.txt 文档中找到的停用词 - 我无法为此使用 nltk。

从本质上说最有效的方法是什么

#For each line you read in input_file.readlines()
  #if a word in input_file is in stopwords
    #append it
  #else 

【问题讨论】:

    标签: python python-3.x file text stop-words


    【解决方案1】:

    您可以使用具有 O(1) 时间复杂度成员资格测试的 set 数据结构:

    stop_words = set(["in", "to", "this", ...])
    if word in stop_words:
        print("discarded")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-27
      • 2019-09-25
      • 1970-01-01
      • 2022-12-24
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      相关资源
      最近更新 更多