将句子从句号,逗号和&中分成几部分但

时间:2018-03-11 18:00:36

标签: python

sentence = "Very disorganized and hard professor. Does not come to classes on time, she grades tough, does not help on anything. She says come for help but when you go to her office hour, she is not there to help."

我想把句子从句号,逗号和&中分成几部分。但。 输出应该是,

Very disorganized 
and hard professor. 
Does not come to classes on time, 
she grades tough, 
does not help on anything. 
She says come for help 
but when you go to her office hour, 
she is not there to help. 

现在我正在使用,

sample = re.split(r' *[\.\?!][\'"\)\]]* *', sentence)

print (sample)

这只能完全停止句子。 输出,

['Very disorganized and hard professor', 'Does not come to classes on time, she grades tough, does not help on anything', 'She says come for help but when you go to her office hour, she is not there to help']

知道怎么做。

3 个答案:

答案 0 :(得分:1)

您可以使用re.sub()添加遇到停用词的换行符。

正则表达式只是:(and|\.|but|,),它与您的停用词匹配。然后用自己替换该组,再加上一个换行符。

>>> import re   
>>> sentence = "Very disorganized and hard professor. Does not come to classes on time, she grades tough, does not help on anything. She says come for help but when you go to her office hour, she is not there to help."  
>>> sample = re.sub(r'(and|\.|but|,)', r'\1\n', sentence)
>>> sample
Very disorganized and
 hard professor.
 Does not come to classes on time,
 she grades tough,
 does not help on anything.
 She says come for help but
 when you go to her office hour,
 she is not there to help.

如果你想要它在列表中:

>>> re.sub(r'(and|\.|but|,)', r'\1\n', sentence).split('\n')
['Very disorganized and', ' hard professor.', ' Does not come to classes on time,', ' she grades tough,', ' does not help on anything.', ' She says come for help but', ' when you go to her office hour,', ' she is not there to help.', '']

如果要在每个后续行之前删除空格,可以使用:

sample = re.sub(r'(and|\.|but|,)(?:\s)', r'\1\n', sentence)

答案 1 :(得分:0)

试试这个

Result=re.split(r'[.,&]', sentence)

答案 2 :(得分:0)

或循环

for x in ['.', ',', 'and', 'but']:
   sentence=sentence.replace(x, x+'\n')

在每个分隔符之后添加\n

输出:

Very disorganized and
 hard professor.
 Does not come to classes on time,
 she grades tough,
 does not help on anything.
 She says come for help but
 when you go to her office hour,
 she is not there to help.