【问题标题】:How to iterate through sentence of string in Python?如何在Python中遍历字符串的句子?
【发布时间】:2012-05-17 08:34:47
【问题描述】:

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

  1. 我需要使用NLTK 库遍历每个单词和词干。词干提取功能是PorterStemmer().stem_word(word)。我们必须传递参数'word'。如何对每个单词进行词干并取回词干的句子?

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

    stopwordsfile = open('c:/stopwordlist.txt','r+')
    stopwordslist=stopwordsfile.read()
    

    如何从text 中删除这些停用词并获得干净的新字符串?

【问题讨论】:

  • for word in text.split(' '): stemmer.stem_word(word)?
  • stemmed = for word in text.split(' '): stemmer.stem_word(word) 可以吗?
  • 不完全是。如果你想要一个词干列表,你可以做stemmed = [stemmer.stem_word(w) for w in text.split(' ')]。如果你想要一个句子,你可以做sente = ' '.join(stemmed),它会返回一个包含所有词干的句子。让我知道这是否有帮助。
  • @birryree 谢谢 :) 我用 " ".join(PorterStemmer().stem_word(word) for word in text.split(" ")) 做到了

标签: python text-segmentation


【解决方案1】:

我将此作为评论发布,但我认为我不妨将其充实为一个完整的答案并进行一些解释:

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

for word in text.split(" "):
    PorterStemmer().stem_word(word)

由于您想将所有词干组合在一起,因此将这些词干重新组合在一起是微不足道的。为了轻松有效地做到这一点,我们使用str.join()generator expression

" ".join(PorterStemmer().stem_word(word) for word in text.split(" "))

编辑:

对于您的其他问题:

with open("/path/to/file.txt") as f:
    words = set(f)

这里我们使用the with statement 打开文件(这是打开文件的最佳方式,因为它可以正确地处理关闭它们,即使在异常情况下也是如此,并且更具可读性)并将内容读入一个集合。我们使用一个集合,因为我们不关心单词的顺序,或者重复,以后会更有效率。我假设每行一个单词 - 如果不是这种情况,并且它们是逗号分隔或空格分隔的,那么像我们之前所做的那样使用str.split()(带有适当的参数)可能是一个好计划。

stems = (PorterStemmer().stem_word(word) for word in text.split(" "))
" ".join(stem for stem in stems if stem not in words)

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

编辑 2:

要在词干之前删除它们,它甚至更简单:

" ".join(PorterStemmer().stem_word(word) for word in text.split(" ") if word not in words)

给定单词的删除很简单:

filtered_words = [word for word in unfiltered_words if not in set_of_words_to_filter]

【讨论】:

  • 我需要做另一件事。从该字符串中删除停用词。存储在文本文件中的停用词列表(空格分隔) stopwordsfile = open('c:/stopwordlist.txt','r+') stopwordslist=stopwordsfile.read() 我需要从text 中删除这些停用词并重新清理字符串。
  • @ChamingaD 我建议这是一个不同的问题,您应该提出一个新问题。如果您这样做,它将对将来遇到类似问题的其他人更有帮助,并且更容易与我们合作。
  • 问题是我必须再等 20 分钟才能开始新的 qustion:/
  • @ChamingaD 我在这里为这个案例添加了一个答案。但是,将来发布一个单独的问题是更好的解决方案。
  • 非常感谢 :) 我可以将停用词删除作为单独的代码吗? (首先我会删除停用词然后词干)
【解决方案2】:

遍历字符串中的每个单词:

for word in text.split():
    PorterStemmer().stem_word(word)

使用字符串的连接方法(Lattyware 推荐)将片段连接成一个大字符串。

" ".join(PorterStemmer().stem_word(word) for word in text.split(" "))

【讨论】:

  • 这个问题确实会问“并得到一个词干的句子”,所以完整的答案是" ".join(PorterStemmer().stem_word(word) for word in text.split(" "))
猜你喜欢
  • 2010-09-18
  • 1970-01-01
  • 2018-10-01
  • 2019-05-29
  • 1970-01-01
  • 2015-03-30
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
相关资源
最近更新 更多