【问题标题】:Finding total number of "stopwords" in a file查找文件中“停用词”的总数
【发布时间】:2016-01-07 14:12:26
【问题描述】:

我正在尝试创建一个 Python 程序来读取两个文本文件,一个包含一篇文章,另一个包含“停用词”列表(每行一个词)。我想确定我正在使用的包含文章的特定文本文件中有多少这些“停用词”(每个“停用词”的频率的累积总数)。

我尝试创建嵌套的for 循环以执行此操作,其中我循环遍历包含文章的文件的每一行(外部 for 循环),并且在每一行内都有一个 for 循环(内部 for 循环)循环遍历“停用词”列表,并查看“停用词”是否在当前行中,如果是,多久出现一次。最后,我将单词在当前行中的频率添加到累加器中,该累加器将跟踪在包含文章的文件中找到的停用词的总累积量。

目前,当我运行它时,它说文件中有0个停用词,这是不正确的。

import string

def main():

    analyzed_file  = open('LearnToCode_LearnToThink.txt', 'r')
    stop_word_file = open('stopwords.txt', 'r')

    stop_word_accumulator = 0

    for analyzed_line in analyzed_file.readlines():

        formatted_line = remove_punctuation(analyzed_line)

        for stop_word_line in stop_word_file.readlines():
            stop_formatted_line = create_stopword_list(stop_word_line)
            if stop_formatted_line in formatted_line:
                stop_word_frequency = formatted_line.count(stop_formatted_line)
                stop_word_accumulator += stop_word_frequency

        print("there are ",stop_word_accumulator, " words")


        stop_word_file.close()
        analyzed_file.close()


def create_stopword_list(stop_word_text):

 clean_words = [] # create an empty list
 stop_word_text = stop_word_text.rstrip() # remove trailing whitespace characters
 new_words = stop_word_text.split() # create a list of words from the text
 for word in new_words: # normalize and add to list
        clean_words.append(word.strip(string.punctuation).lower())
 return clean_words



def remove_punctuation(text):
    clean_words = [] # create an empty list
    text = text.rstrip() # remove trailing whitespace characters
    words = text.split() # create a list of words from the text
    for word in words: # normalize and add to list
        clean_words.append(word.strip(string.punctuation).lower())
    return clean_words


main()

【问题讨论】:

    标签: python for-loop readfile readlines


    【解决方案1】:

    你有很多问题:

    1. readlines 只会工作一次 - 之后,您将位于文件的末尾,它将返回一个空字符串。
    2. 无论如何,为其他文件中的每一行重新创建停用词列表的效率非常低。
    3. one_list in another_listone_list.count(another_list) 不要做你认为他们做的事。

    请尝试以下方法:

    stop_words = get_stop_word_list(stop_words_file_name)
    
    stop_word_count = 0
    
    with open(other_file_name) as other_file:  # note 'context manager' file handling
        for line in other_file:
            cleaned_line = clean(line)
            for stop_word in stop_words:
                if stop_word in cleaned_line:
                    stop_word_count += cleaned_line.count(stop_word)
    

    有更有效的方法(例如使用sets 和collections.Counters),但这应该可以帮助您入门。

    【讨论】:

    • 我建议用stop_word_count += sum(map(cleaned_line.count, stop_words))替换内部for循环(也许用imap替换map)。在致电count 之前,您是否有理由检查该词是否存在?
    • 好的,我会试试@jonrsharpe,让你知道它是否有效,如果它不会发布我修改它的代码
    • @AlexHall 主要是为了让它合理地接近 OP 目前正在尝试做的事情!它只比你建议的效率低一点,如果你使用字典,你真的可以在每一行上只通过一次。
    • @heyyo9028 你在开玩笑吧?缩进在 Python 中很重要,我们应该如何在注释框中阅读它?获取rubber duck
    • 好的,我将把我现在拥有的内容放在我原来的帖子中
    【解决方案2】:

    您可以使用 NLTK 来检查停用词并对其进行计数:

    from nltk.corpus import stopwords
    nltk.download('stopwords')
    from nltk.tokenize import word_tokenize 
    nltk.download('punkt')
    
    x = r"['Nel mezzo del cammin di nostra vita mi ritrovai per una selva oscura, ché la 
    diritta via era smarrita.Ahi quanto a dir qual era è cosa dura esta selva selvaggia 
    e aspra e forte che nel pensier rinova la paura! Tant' è amara che poco è più morte; 
    ma per trattar del ben ch'i' vi trovai, dirò de l altre cose chi v ho scorte.']"
    
    word_tokens = word_tokenize(x) #splitta i pezzi
    
    stopwords_x = [w for w in word_tokens if w in stopWords]
    len(stopwords_x) / len(word_tokens) * 100
    

    【讨论】:

    • '''stopwords_x = [w for w in word_tokens if w in stopwords.words('english)]''' 为我工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多