还有其他方法可以做到这一点:
>>> 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']]
答案 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
的字词)。