拆分字符串Python

时间:2015-04-04 05:22:58

标签: python-3.x

还有其他方法可以做到这一点:

>>> in_string = "Hello, world! how are you? Your oceans are pretty. Incomplete sentence"

>>> def sep_words(string_1):
"""Function which takes a string and returns a list of lists contining the words"""

        list_1 = string_1.split()
        list_output = []
        list_temp = []
    for i in list_1:
        if ((i[-1] == '!') or (i[-1] == '?') or (i[-1] == '.')):
            list_temp.append(i[:-1])
            list_temp.append(i[-1:])
            list_output.append(list_temp)
            list_temp = []
        else:
            list_temp.append(i)
    if list_temp == []:
        pass
    else:
        list_output.append(list_temp)
    print (list_output)


>>> sep_words(in_string)

[['Hello,', 'world', '!'], ['how', 'are', 'you', '?'], ['Your', 'oceans', 'are', 'pretty', '.'], ['Incomplete', 'sentence']]

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式:

import re
message = "Hello, world! how are you? Your oceans are pretty. Incomplete sentence"
print re.findall(r"[A-Za-z,]+|\S", message)

输出:

['Hello,', 'world', '!', 'how', 'are', 'you', '?', 'Your', 'oceans', 'are', 'pretty', '.', 'Incomplete', 'sentence']

该表达式查找包含一个或多个(+)个字母以及可能包含逗号([A-Za-z,])或(|)非空白字符(\S的字词)。