如何在Python中迭代字符串的句子?

Cha*_*gaD 6 python text-segmentation

假设我有一个字符串text = "A compiler translates code from a source language".我想做两件事:

  1. 我需要使用NLTK库迭代每个单词和词干.阻止的功能是PorterStemmer().stem_word(word).我们必须传递"单词"这个论点.如何阻止每个单词并取回词干?

  2. 我需要从text字符串中删除某些停用词.包含停用词的列表存储在文本文件中(空格分隔)

    stopwordsfile = open('c:/stopwordlist.txt','r+')
    stopwordslist=stopwordsfile.read()
    
    Run Code Online (Sandbox Code Playgroud)

    如何从中删除这些停用词text并获取已清理的新字符串?

Gar*_*tty 9

我发布这个评论作为评论,但我想我可能会把它充实为一个完整的答案,并附上一些解释:

您想使用str.split()将字符串拆分为单词,然后阻止每个单词:

for word in text.split(" "):
    PorterStemmer().stem_word(word)
Run Code Online (Sandbox Code Playgroud)

当你想要将所有词干的字符串组合在一起时,将这些词汇重新组合在一起是微不足道的.要轻松有效地执行此操作,我们使用str.join()生成器表达式:

" ".join(PorterStemmer().stem_word(word) for word in text.split(" "))
Run Code Online (Sandbox Code Playgroud)

编辑:

对于你的其他问题:

with open("/path/to/file.txt") as f:
    words = set(f)
Run Code Online (Sandbox Code Playgroud)

在这里,我们打开使用该文件with声明(这是打开文件的最好方法,因为它处理正确关闭它们,甚至在例外情况,更可读的),并读取其中的内容为一组.我们使用一个集合,因为我们不关心单词的顺序或重复,后来它会更有效.我假设每行一个字 - 如果不是这样,并且它们以逗号分隔,或者空格分隔,那么使用str.split()我们之前使用的(使用适当的参数)可能是一个很好的计划.

stems = (PorterStemmer().stem_word(word) for word in text.split(" "))
" ".join(stem for stem in stems if stem not in words)
Run Code Online (Sandbox Code Playgroud)

这里我们使用生成器表达式的if子句来忽略我们从文件加载的单词集中的单词.对集合的成员资格检查是O(1),因此这应该是相对有效的.

编辑2:

要在它们被阻止之前删除它们,它甚至更简单:

" ".join(PorterStemmer().stem_word(word) for word in text.split(" ") if word not in words)
Run Code Online (Sandbox Code Playgroud)

删除给定的单词只是:

filtered_words = [word for word in unfiltered_words if not in set_of_words_to_filter]
Run Code Online (Sandbox Code Playgroud)