【问题标题】:How to read tokens from a file one by one in Python?如何在 Python 中从文件中一一读取令牌?
【发布时间】:2018-01-18 22:16:15
【问题描述】:

我遇到的问题是,在我的代码中,我无法让单个单词/标记与停用词匹配以从原始文本中删除。相反,我得到了一个完整的句子,因此无法将它与停用词匹配。请告诉我一种获取单个标记的方法,然后将它们与停用词匹配并删除它们。请帮帮我。

from nltk.corpus import stopwords
import string, os
def remove_stopwords(ifile):
    processed_word_list = []
    stopword = stopwords.words("urdu")
    text = open(ifile, 'r').readlines()
    for word in text:
         print(word)
         if word  not in stopword:
                processed_word_list.append('*')
                print(processed_word_list)
                return processed_word_list

if __name__ == "__main__":
    print ("Input file path: ")
    ifile = input()
    remove_stopwords(ifile)

【问题讨论】:

  • 您没有得到文本中的单词的原因是因为您正在使用readlines() 函数。这为您提供了文件中的行/句子的可迭代,然后当您说 for word in text: 时,您将逐行获取。

标签: python python-3.x token nltk stop-words


【解决方案1】:

试试这个:

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import string, os, ast
def remove_stopwords(ifile):
    processed_word_list = []
    stopword = stopwords.words("urdu")
    words = ast.literal_eval(open(ifile, 'r').read())
    for word in words:
        print(word)
        if word not in stopword:
            processed_word_list.append('*')
        else:
            processed_word_list.append(word)
    print(processed_word_list)
    return processed_word_list

if __name__ == "__main__":
    print ("Input file path: ")
    ifile = input()
    remove_stopwords(ifile)

【讨论】:

  • 这不起作用,因为line 是一个字符串,因此您将遍历line 中的字符。将line 换成line.split(),我们就可以开始了。
  • 这段代码只给了我第一个单词,然后它就终止了。我无法获取整个列表,而只能获取文件中的第一个单词。我希望它迭代并将给定文本文件中的所有单词与停用词匹配,并显示没有停用词或已删除停用词的列表。
  • 当我提供的文件已经被标记化时,.split() 函数也会生成标记。
  • 它在第一个单词之后退出的原因是因为return 语句必须在for 循环之外。我编辑了上面的代码。它现在对我有用。
  • 你的意思是你的输入文件每行已经有一个单词了吗?在这种情况下,上述内容可以简化,但它仍然可以工作。
猜你喜欢
  • 2018-03-23
  • 2019-04-01
  • 2011-02-28
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多