那些字符串不是包含一个单词吗? “蒸发”和“阳光”单字?在我看来,您想保留一元组,而不是删除它们。
您可以使用列表推导来做到这一点:
list1 = ['water vapor','evaporation','carbon dioxide','sunlight','green plants']
unigrams = [word for word in list1 if ' ' not in word]
>>> print unigrams
['evaporation', 'sunlight']
这假定单词由一个或多个空格分隔。这对于 n > 1 的 n-gram 的构成可能过于简单化,因为不同的空白字符可以分隔单词,例如制表符、换行符、各种空白 unicode 代码点等。您可以使用 regular expression :
import re
list1 = ['water vapor','evaporation','carbon dioxide','sunlight','green plants', 'word with\ttab', 'word\nword', 'abcd\refg']
unigram_pattern = re.compile('^\S+$') # string contains only non-whitespace chars
unigrams = [word for word in list1 if unigram_pattern.match(word)]
>>> print unigrams
['evaporation', 'sunlight']
模式^\S+$ 表示匹配从字符串开头到字符串结尾的所有非空白字符。
如果需要支持 unicode 空格,可以在编译模式时指定 unicode 标志:
list1.extend([u'punctuation\u2008space', u'NO-BREAKu\u00a0SPACE'])
unigram_pattern = re.compile('^\S+$', re.UNICODE)
unigrams = [word for word in list1 if unigram_pattern.match(word)]
>>> print unigrams
['evaporation', 'sunlight']
现在它还会过滤掉那些包含 unicode 空格的字符串,例如不间断空格 (U+00A0) 和标点空格 (U+2008)。