gpt4 book ai didi

python - 每次有标点符号时将字符串拆分成句子,标点符号?

转载 作者:行者123 更新时间:2023-12-04 09:43:54 31 4
gpt4 key购买 nike

我想将字符串拆分为列表中的单独句子。

例子:

string = "Hey! How are you today? I am fine."

输出应该是:

["Hey!", "How are you today?", "I am fine."]

最佳答案

您可以使用内置的正则表达式库。

import re
string = "Hey! How are you today? I am fine."
output = re.findall(".*?[.!\?]", string)

output>> ['Hey!', ' How are you today?', ' I am fine.']

更新:

您可以使用 split()方法,但它不会返回用于拆分的字符。
import re
string = "Hey! How are you today? I am fine."
output = re.split("!|?", string)
output>> ['Hey', ' How are you today', ' I am fine.']

如果这对您有用,您可以使用 replace()split() .
string = "Hey! How are you today? I am fine."
output = string.replace("!", "?").split("?")

关于python - 每次有标点符号时将字符串拆分成句子,标点符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62207291/

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