【问题标题】:How to get unigrams (words) from a list in python?如何从 python 的列表中获取 unigrams(单词)?
【发布时间】:2015-11-26 09:42:20
【问题描述】:

输入为list1=['水蒸气','蒸发','二氧化碳','阳光','绿色植物']

输出应该是

list1=['evaporation','sunlight']
for i in list1:
    " " not in i
    print i

False - water vapor
True - evaporation
False - carbon dioxide
True - sunlight
False - green plants

【问题讨论】:

  • 你尝试过任何东西吗?
  • 是的,我试过了。但没有得到这个输出
  • 请发布您尝试过的代码和结果。
  • 您因为没有发布任何代码而被否决,请尝试发布您的代码
  • 我猜您想删除包含多个单词的项目。你试过什么没用?

标签: python


【解决方案1】:

如果需要根据条件从列表中删除元素,可以使用filter()list comprehension

您了解检查非单字词的方法:" " in word

基本上,如果你想使用 for 循环构造一个新列表,你可以这样写:

new_list = []
for word in words:
    if " " in word:  # This is not an unigram word
        new_list.append(word)

这可以更简单,这要归功于 Python 语法:

new_list = [word for word in words if " " in word]

或者:

new_list = list(filter(lambda word: " " in word, words))

两者都将返回非单字词列表,如您的问题标题中所述(即使您的示例返回单字词......)

【讨论】:

    【解决方案2】:

    那些字符串不是包含一个单词吗? “蒸发”和“阳光”单字?在我看来,您想保留一元组,而不是删除它们。

    您可以使用列表推导来做到这一点:

    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)。

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 1970-01-01
      • 2011-10-23
      • 2011-02-17
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      相关资源
      最近更新 更多