gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:22 25 4
gpt4 key购买 nike

所以我有以下字符串:

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)

关于python - 我可以将一个字符串拆分成一个嵌套列表,其中外部列表​​包含每个句子的列表,内部列表包含每个句子的单词吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33454544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com