将一组字符串句子转换为单词列表

7
我正在尝试将一系列包含句子的字符串转换为列表,例如:
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]

我知道我在犯一个愚蠢的错误,但我想不出为什么,有人可以帮忙吗?

5个回答

19

您需要使用str.split()将每个字符串分割成单词:

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

再次感谢,我知道我漏掉了一些简单的东西,非常感激! - George Burrows
这应该是[word for line in sentence for word in line.split()] - Andrew Clark
1
点赞了,不过请记住,在列表推导式中使用超过2个迭代子句通常是不被赞同的。 - user3023451
我知道这已经有一段时间了,但我能否得到关于代码的解释?我理解[line for line in sentence],但我不理解第二部分for word in line.split()。它与[line.split() for line in sentence]有什么不同? - addicted
一个重要的语法是使用单个列表符号来实现多个 for 循环,谢谢。 - shantanu pathak

7

只需使用 .split.join 方法:

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

4

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

您可以使用.split(' ')将字符串按空格分割。 所以这样做就可以:

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

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

-1

将句子分割成单词:

print(sentence.rsplit())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接