代码之家  ›  专栏  ›  技术社区  ›  user3778289

如何在Python中逐个读取文件中的令牌?

  •  2
  • user3778289  · 技术社区  · 8 年前

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

    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)
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   M3RS    8 年前

    试试这个:

    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)