python讀取txt文件以空行做爲數據的切分處理

先舉個例子,以下test.txt文件數據,須要提取每條數據的title和content, 單獨保存到文件中:app

spiderTime:{'num':'12223'}
title:中國保險1xxx
summary: 請在xxx
content: 當事人11sfdffghfhgfjjd
tag:1

spiderTime:{'num':'12224'}
title:中國保險2xxx
summary: 請在xxx
content: 當事人22sfdfffdffghfjd
tag:2

spiderTime:{'num':'12225'}
title:中國保險3xxx
summary: 請在xxx
content: 當事人33sfdffggghfjd
tag:3

首先發現,數據是以空行做爲分割點,因此,能夠以空行拆分數據,作處理,具體代碼以下:ide

with open('test.txt','r',encoding='utf8') as f:
    cont = True
    li = []
    while cont:
        cont = f.readline()
        li.append(cont)
        if cont =='\n':
            print(li)
            title = re.findall(r"\'title:(.*?)\\n\'\,", str(li))[0]
            content = re.findall(r"\'content:(.*?)\\n\'\,", str(li))[0]
            print('title: {}'.format(title))
            print('content: {}'.format(content))
            print('==' * 20)
            li = []

上述代碼中經過正則進行匹配title和content內容,若是它們在每條數據中的行號固定的話,簡單些能夠直接經過列表索引取值. 代碼運行輸出結果以下:spa

["spiderTime:{'num':'12223'}\n", 'title:中國保險1xxx\n', 'summary: 請在xxx\n', 'content: 當事人11sfdffghfhgfjjd\n', 'tag:1\n', '\n']
title: 中國保險1xxx
content:  當事人11sfdffghfhgfjjd
========================================
["spiderTime:{'num':'12224'}\n", 'title:中國保險2xxx\n', 'summary: 請在xxx\n', 'content: 當事人22sfdfffdffghfjd\n', 'tag:2\n', '\n']
title: 中國保險2xxx
content:  當事人22sfdfffdffghfjd
========================================
["spiderTime:{'num':'12225'}\n", 'title:中國保險3xxx\n', 'summary: 請在xxx\n', 'content: 當事人33sfdffggghfjd\n', 'tag:3\n', '\n']
title: 中國保險3xxx
content:  當事人33sfdffggghfjd
========================================

 思路總結:  按行循環讀取數據, 當讀取到換行符時(注意,換行符'\n'不等於空,切記), 做爲一個切分點標記,能夠把以前讀取到的利用列表或字符串拼接構成一個總體,再使用正則進行數據提取, 當讀取的書記爲null是,自動結束循環; 上述代碼要注意的一點就是txt文件最後有內容的一行後面須要再有兩行換行,不然最後一條數據會讀取丟失.code

相關文章
相關標籤/搜索