【问题标题】:Getting word count from a python list从 python 列表中获取字数
【发布时间】:2014-09-21 02:38:18
【问题描述】:

我无法计算列表中的单词。

My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]

我需要脚本输出的是列表中的单词数(在本例中为 15 个)。

len(My_list)

将返回“4”(项目数)。

for item in My_list:
    print len(item.split())

会给我每个项目的长度。

有没有办法从列表中获取字数? 理想情况下,我还想将每个单词附加到一个新列表中(每个单词都是一个项目)。

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用以下命令生成所有单个单词的列表:

    words = [word for line in My_list for word in line.split()]
    

    数单词,请使用sum()

    sum(len(line.split()) for line in My_list)
    

    演示:

    >>> My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]
    >>> [word for line in My_list for word in line.split()]
    ['white', 'is', 'a', 'colour', 'orange', 'is', 'a', 'fruit', 'blue', 'is', 'a', 'mood', 'I', 'like', 'candy']
    >>> sum(len(line.split()) for line in My_list)
    15
    

    【讨论】:

      【解决方案2】:

      要查找每个项目中单词的总和:

      sum (len(item.split()) for item in My_list)
      

      将所有单词放在一个列表中:

      sum ([x.split() for x in My_list], [])
      

      【讨论】:

        【解决方案3】:

        列表理解是一个非常好的主意。另一种方法是使用 join 和 split:

        l = " ".join(My_list).split()
        

        现在 'l' 是一个列表,其中包含所有单词标记作为项目,您可以简单地在其上使用 len():

        len(l)
        

        【讨论】:

          【解决方案4】:

          你总是可以选择简单的循环。

          My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]
          
          c = 0
          for item in My_list:
              for word in item.split():
                  c += 1
          
          print(c)
          

          【讨论】:

            【解决方案5】:
            My_list = ["white is a colour", "orange is a fruit", "blue is a mood", "I like candy"]
            
            word_count = 0
            for phrase in My_list:
                # increment the word_count variable by the number of words in the phrase.
                word_count += len(phrase.split())
            
            print word_count
            

            【讨论】:

              猜你喜欢
              • 2016-01-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-03-26
              • 1970-01-01
              • 2023-01-24
              • 2015-11-23
              • 1970-01-01
              相关资源
              最近更新 更多