如何将字符串拆分为列表?

2024-04-25 16:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望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)

Tags: the函数代码textin列表fordef
3条回答

str.split()

Return a list of the words in the string, using sep as the delimiter ... If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

>>> line="a sentence with a few words"
>>> line.split()
['a', 'sentence', 'with', 'a', 'few', 'words']
>>> 
text.split()

这应该足够存储列表中的每个单词。words已经是句子中单词的列表,因此不需要循环。

第二,可能是输入错误,但你的循环有点混乱。如果您真的想使用append,它将是:

words.append(word)

不是

word.append(words)

text中对任何连续的空白行拆分字符串。

words = text.split()      

在分隔符text中拆分字符串:","

words = text.split(",")   

words变量将是一个list,并且包含分隔符上text中拆分的单词。

相关问题 更多 >