Skip to main content
 首页 » 编程设计

python之我可以将一个字符串拆分成一个嵌套列表,其中外部列表包含每个句子的列表,内部列表包含每个句子的单词吗

2025年05月04日31zhengyun_ustc

所以我有以下字符串:

string1 = " This is random text! I am trying to split this text into a nested list. Where each sentence is its own list and the values of that list contain the words and punctuation of that sentence. Is this possible? If not, why not? " 

我需要将其拆分为如下所示的嵌套列表。

nested_list = [["This", "is", "random", "text", "!"] ["I", "am", "trying", "to", "split", "this", "text", "into", "a", "nested", "list", "."], ["Where", "each", "sentence", "is", "its", "own", "list", "and", "the", "values", "of", "that", "list", "contain", "the", "words", "and", "punctuation", "of", "that", "sentence", "."], ["Is", "this", "possible", "?"], ["If", "not", ",", "why", "not", "?"]] 

我知道 string.split() 方法可以带参数,但我想不出在所有句点、问号和感叹号处拆分段落。因为根据我的理解,string.split() 只接受一个参数。

请您参考如下方法:

你可以使用 python 内置:

import re 
re.split(r'[!?.|,|\*|\n]',string1)