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

7 投票
5 回答
21310 浏览
提问于 2025-04-17 08:14

我正在尝试处理一个包含句子的字符串列表,比如:

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 个回答

4

你没有告诉它怎么区分一个单词。默认情况下,遍历一个字符串就是逐个字符地查看。

你可以使用 .split(' ') 来通过空格把字符串分开。所以这样做就可以了:

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

只需要用 .split.join 就可以了:

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

你需要用 str.split() 这个方法来把每个字符串分割成单词:

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

撰写回答