2014-12-05 65 views
0

我有一个字符串列表,我想删除每个字符串中的停用词。问题是,停用词的长度比字符串长得多,我不想重复比较每个字符串和停用词列表。 python中有多种方式可以同时使用这些多个字符串吗?python同时处理多个字符串

lis = ['aka', 'this is a good day', 'a pretty dog'] 
stopwords = [] # pretty long list of words 
for phrase in lis: 
    phrase = phrase.split(' ') # get list of words 
    for word in phrase: 
     if stopwords.contain(word): 
      phrase.replace(word, '') 

这是我目前的方法。但是这意味着我必须经历列表中的所有短语。有没有一种方法可以用一次比较来处理这些短语?

谢谢。

+0

“长”要多长时间?如果它不到10万个元素,我不会担心。特别是如果你将'stopwords'放入一个集合中,因为'set in set x'检查速度非常快。 – Kevin 2014-12-05 16:26:31

+0

一个嵌套的列表理解陈述可能会更好(或更混乱?)看,但这是非常好的方式,我可以看到做到这一点 – TehTris 2014-12-05 16:28:59

+0

@Kevin嗯,它是10万长,但仍然不想以检查多次.. – JudyJiang 2014-12-05 16:29:41

回答

3

这是一样的想法,但有一些改进。将您的list停用词转换为set以加快查找速度。然后,您可以遍历列表理解中的短语列表。然后你可以迭代短语中的单词,如果它们不在停止集中,则保留它们,然后将短语重新组合在一起。

>>> lis = ['aka', 'this is a good day', 'a pretty dog'] 
>>> stopwords = ['a', 'dog'] 
>>> stop = set(stopwords) 
>>> [' '.join(j for j in i.split(' ') if j not in stop) for i in lis] 
['aka', 'this is good day', 'pretty'] 
1

您可以计算每个短语形成的列表与停用词之间的差异。

>>> lis = ['aka', 'this is a good day', 'a pretty dog'] 
>>> stopwords = ['a', 'dog'] 

>>> stop = set(stopwords) 
>>> result = map(lambda phrase: " ".join(list(set(phrase.split(' ')) - stop)), lis) 
>>> print(result) 

['aka', 'this is good day', 'pretty'] 
+1

实际上,由于您对分组进行了分组,因此它会混淆词组中的单词的顺序。与''=''a b c d e f g''''它给'''''''''''''。 – Dettorer 2014-12-05 17:02:43