【问题标题】:Convert a list of string sentences to words将字符串句子列表转换为单词
【发布时间】:2012-01-18 16:47:58
【问题描述】:

我试图从本质上获取一个包含以下句子的字符串列表:

sentence = ['Here is an example of what I am working with', 'But I need to change the format', 'to something more useable']

并将其转换为以下内容:

word_list = ['Here', 'is', 'an', 'example', 'of', 'what', 'I', 'am',
'working', 'with', 'But', 'I', 'need', 'to', 'change', 'the format',
'to', 'something', 'more', 'useable']

我试过用这个:

for item in sentence:
    for word in item:
        word_list.append(word)

我认为它会获取每个字符串并将该字符串的每个项目附加到 word_list,但是输出类似于:

word_list = ['H', 'e', 'r', 'e', ' ', 'i', 's' .....etc]

我知道我犯了一个愚蠢的错误,但我不知道为什么,谁能帮忙?

【问题讨论】:

    标签: python string sentence


    【解决方案1】:

    分词:

    print(sentence.rsplit())
    

    【讨论】:

      【解决方案2】:

      您需要str.split() 将每个字符串拆分为单词:

      word_list = [word for line in sentence for word in line.split()]
      

      【讨论】:

      • 再次感谢,我知道我错过了这样简单的东西,非常感谢!
      • 这应该是[word for line in sentence for word in line.split()]
      • 赞成,尽管在列表理解中通常不赞成超过 2 个迭代子句。
      • 我知道这已经有一段时间了,但我能得到关于代码的解释吗?我了解[line for line in sentence],但我不了解后半部分for word in line.split()。和[line.split() for line in sentence] 有什么区别?
      • 这里要学习的一个重要语法是带有多个 for 循环的单个列表表示法,谢谢 ..
      【解决方案3】:
      for item in sentence:
          for word in item.split():
              word_list.append(word)
      

      【讨论】:

        【解决方案4】:

        你还没有告诉它如何区分单词。默认情况下,遍历字符串只是遍历字符。

        您可以使用.split(' ') 以空格分隔字符串。所以这会起作用:

        for item in sentence:
            for word in item.split(' '):
                word_list.append(word)
        

        【讨论】:

          【解决方案5】:

          只需.split.join

          word_list = ' '.join(sentence).split(' ')
          

          【讨论】:

            猜你喜欢
            • 2011-09-05
            • 1970-01-01
            • 2018-10-17
            • 1970-01-01
            • 2020-04-02
            • 2011-06-08
            • 1970-01-01
            • 2015-05-25
            • 1970-01-01
            相关资源
            最近更新 更多