- 问题:
-
我希望我的Python函数分割一个句子(输入),并将每个单词存储在一个列表中。我当前的代码会拆分句子,但不会将单词存储为列表。我该怎么做?在
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(words)
- 答案:
-
text.split()
这应该足够存储列表中的每个单词。
单词
已经是句子中单词的列表,因此不需要循环第二,可能是打字错误,但你的循环有点混乱。如果您真的想使用append,它将是:
words.append(word)
不是
word.append(words)