python 拼接误换行句子代码

有些文本在解析出来的时候,换行出现了问题,比如:“今天天气很好啊\n所以我出来玩了。”因此我们需要将误换行的句子拼接起来。

一开始打算是用递归的思想去做,后面发现python的list也可以用pop,就直接pop更方便了,时间复杂度的话就是O(n)。

import re

sentence_list = ['大家按时打卡的。', '的空间马上到', '肯定撒老大', '健康大使的。','打卡十六点。', '大苏打撒旦!']
end_flag = re.compile('.*[。!]$')	# 句子的结束符,可以自己定义更多。

normal_list = []
try:
    for r in range(len(sentence_list)):
        if end_flag.findall(sentence_list[0]) != []:
            se = sentence_list.pop(0)
            normal_list.append(se)
        else:
            sentence_list[0] += sentence_list[1]
            sentence_list.pop(1)
except IndexError:
    print('拼接完毕')

print(normal_list)

得到的结果如下:

['大家按时打卡的。', '的空间马上到肯定撒老大健康大使的。', '打卡十六点。', '大苏打撒旦!']

猜你喜欢

转载自blog.csdn.net/sinat_33455447/article/details/103552101