有些文本在解析出來的時候,換行出現了問題,比如:“今天天氣很好啊\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)
得到的結果如下:
['大家按時打卡的。', '的空間馬上到肯定撒老大健康大使的。', '打卡十六點。', '大蘇打撒旦!']