2011-12-12 55 views
4

我想基本上采取串方含句子,如清单列表:字符串转换句子的单词

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,但是OUTP UT是沿着线的东西:

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

我知道我在做一个愚蠢的错误,但我想不出为什么,谁能帮助?

回答

11

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

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

再次感谢,我知道我失去了一些东西很容易这样,非常感谢! –

+0

这应该是'[line.split()]中单词的句子中的单词。 –

+1

Upvoted,尽管保存在我的迭代中的2个以上的子句通常在列表解析中被忽略。 –

8

只是.split.join

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

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

您可以使用.split(' ')以空格分隔字符串。因此,这会工作:

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

拆分句子翻译成一句话:

print(sentence.rsplit()) 
相关问题