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]

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

4

5 回答 5

18

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

word_list = [word for line in sentence for word in line.split()]
于 2011-12-12T17:55:08.607 回答
7

只是.split.join

word_list = ' '.join(sentence).split(' ')
于 2011-12-12T17:55:14.717 回答
4

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

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

for item in sentence:
    for word in item.split(' '):
        word_list.append(word)
于 2011-12-12T17:55:29.300 回答
2
for item in sentence:
    for word in item.split():
        word_list.append(word)
于 2011-12-12T17:56:01.953 回答
-1

将句子拆分成单词:

print(sentence.rsplit())
于 2017-12-12T13:10:48.967 回答