【问题标题】:Remove stop words in text file without NLTK在没有 NLTK 的情况下删除文本文件中的停用词
【发布时间】:2021-03-25 19:05:15
【问题描述】:

我有 2 个文件:stopwords.txta.txt
我想从文件a.txt 中的文件stopwords.txt 中删除停用词,并用空格分隔。

我该怎么做?这是我试图做的:

def remove_stopwords(review_words):
with open('stopwords.txt') as stopfile:
    stopwords = stopfile.read()
    list = stopwords.split()
    print(list)
    with open('a.txt') as workfile:
        read_data = workfile.read()
        data = read_data.split()
        print(data)
        for word1 in list:
            for word2 in data:
                if word1 == word2:
                    return data.remove(list)
                    print(remove_Stopwords)

提前致谢

【问题讨论】:

标签: python python-3.x


【解决方案1】:

这是一个例子:

k = []
z = []
with open('stopWords.txt', 'r') as f:
   for word in f:
        word = word.split('\n')
        k.append(word[0])

with open('a.txt', 'r') as f_obj:
    for u in f_obj:
        u = u.split('\n')
        z.append(u[0])

p = [t for t in z if t not in k]
print(p)

遍历停用词文件中的每个单词并将其附加到一个列表中,然后遍历另一个文件中的每个单词。执行列表理解并删除出现在停用词列表中的每个单词。

【讨论】:

    【解决方案2】:

    a.txt:

    good great bad
    

    stopwords.txt:

    good bad
    

    也许:

    with open('a.txt','r') as f, open('stopwords.txt','r') as f2:
       a=f.read().split();b=f2.read().split()
       print(' '.join(i for i in a if i.lower() not in (x.lower() for x in b)))
    

    【讨论】:

    • 当您计划在不使用 NLTK 之类的框架的情况下删除停用词时,这只是一个一般性的事情(并不是您问题的真正答案,但至少是您可能想要包含的一句话)有一个您需要考虑的几件事。 1)考虑词干。即你想删除复数,这样如果“狗”被认为是一个停用词,那么狗也应该被删除。有几种方法可以做到这一点... ==> 删除单词末尾的所有 s,或者复制您的停用词并为每个停用词添加一个 s,或者使用 len() 方法查看某个部分是否准确从 0 开始匹配。
    • @Clueless_captain 好了很多东西,编辑我的答案,如果你愿意,我会批准
    • 您可能要考虑的第二件事(最好在词干之前完成)。就是去掉所有的大写;在 Python 中 ' "Hello" == "hello" ' 会返回 'False',所以它不被认为是相同的。您可以尝试的另一件事是删除所有短词。
    • @Clueless_captain 编辑我的
    猜你喜欢
    • 2021-04-27
    • 2023-01-26
    • 2019-01-21
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2018-06-03
    • 2021-09-16
    相关资源
    最近更新 更多