Geo*_*ows 4 python string sentence
我试图基本上采用包含句子的字符串列表,例如:
sentence = ['Here is an example of what I am working with', 'But I need to change the format', 'to something more useable']
Run Code Online (Sandbox Code Playgroud)
并将其转换为以下内容:
word_list = ['Here', 'is', 'an', 'example', 'of', 'what', 'I', 'am',
'working', 'with', 'But', 'I', 'need', 'to', 'change', 'the format',
'to', 'something', 'more', 'useable']
Run Code Online (Sandbox Code Playgroud)
我试过用这个:
for item in sentence:
for word in item:
word_list.append(word)
Run Code Online (Sandbox Code Playgroud)
我认为它会占用每个字符串并将该字符串的每个项目附加到word_list,但输出的内容如下:
Run Code Online (Sandbox Code Playgroud)word_list = ['H', 'e', 'r', 'e', ' ', 'i', 's' .....etc]
我知道我犯了一个愚蠢的错误,但我无法弄清楚为什么,任何人都可以帮忙吗?
Sve*_*ach 14
您需要str.split()将每个字符串拆分为单词:
word_list = [word for line in sentence for word in line.split()]
Run Code Online (Sandbox Code Playgroud)