Python 每次有标点符号的时候就把字符串分成句子,用标点符号吗?
我想把一个字符串分成一个列表中的独立句子 例如:Python 每次有标点符号的时候就把字符串分成句子,用标点符号吗?,python,Python,我想把一个字符串分成一个列表中的独立句子 例如: string = "Hey! How are you today? I am fine." 输出应为: [“嘿!”,“你今天好吗?”,“我很好。”] 您可以使用方法esplit() 你可以试试 >>> a='Beautiful, is; better*than\nugly' >>> import re >>> re.split('; |, |\*|\n',a) ['Beautiful', '
string = "Hey! How are you today? I am fine."
输出应为:
[“嘿!”,“你今天好吗?”,“我很好。”]
您可以使用方法e
split()
你可以试试
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
您可以使用内置的正则表达式库
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()
你不需要正则表达式。只需创建您自己的生成器:
def split_punc(text):
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
# Alternatively, can use:
# from string import punctuation
j = 0
for i, x in enumerate(text):
if x in punctuation:
yield text[j:i+1]
j = i + 1
return text[j:i+1]
你好,我刚刚在vscode上试过这个,输出的仍然是一整句话,['嘿!你今天好吗?我很好。]@KaramMohamed,你试过上面的代码片段了吗?@rose忘了提到你必须重新导入
string = "Hey! How are you today? I am fine."
output = string.replace("!", "?").split("?")
def split_punc(text):
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
# Alternatively, can use:
# from string import punctuation
j = 0
for i, x in enumerate(text):
if x in punctuation:
yield text[j:i+1]
j = i + 1
return text[j:i+1]
list(split_punc(string))
# ['Hey!', ' How are you today?', ' I am fine.']