如何在 Python 中從結構化字串中提取所需資料?
介紹...
我將向您展示幾種從結構化字串中提取所需資料/欄位的方法。這些方法將有助於在輸入結構的格式為已知格式的情況下。
操作方法..
1. 讓我們建立一個虛擬格式來理解這種方法。
Report: <> - Time: <> - Player: <> - Titles: - Country: <>
報告:Daily_Report - 時間:2020-10-16T01:01:01.000001 - 玩家:費德勒 - 冠軍:20 - 國家:瑞士
report = 'Report: Daily_Report - Time: 2020-10-10T12:30:59.000000 - Player: Federer - Titles: 20 - Country: Switzerland'
2. 我從報告中注意到的第一件事是分隔符,它是“-”。我們將繼續使用“-”解析報告。
fields = report.split(' - ') name, time, player , titles, _ = fields print(f"Output \n *** The report name {name} generated on {time} has {titles} titles for {player}. ")
輸出
*** The report name Report: Daily_Report generated on Time: 2020-10-10T12:30:59.000000 has Titles: 20 titles for Player: Federer.
3. 現在輸出並不像預期的那樣,因為我們仍然可以看到一些不需要的標籤,如 Report:、Time:、Player:。
# extract only report name formatted_name = name.split(':')[1] # extract only player formatted_player = player.split(':')[1] # extract only titles formatted_titles = int(titles.split(':')[1]) # extract only titles new_time = time.split(': ')[1] print(f"Output \n {formatted_name} , {new_time}, {formatted_player} , {formatted_titles}")
輸出
Daily_Report , 2020-10-10T12:30:59.000000, Federer , 20
4. 現在時間戳採用 ISO 格式,如果需要,可以拆分,也可以保持原樣。讓我向您展示如何拆分時間戳欄位。
from datetime import datetime formatted_date = datetime.fromisoformat(new_time) print(f"Output \n{formatted_date}")
輸出
2020-10-10 12:30:59
現在,我們將把所有這些步驟組合到一個函式中。
def parse_function(log): """ Function : Parse the given log in the format Report: <> - Time: <> - Player: <> - Titles: - Country: <> Args : log Return : required data """ fields = log.split(' - ') name, time, player , titles, _ = fields # extract only report name formatted_name = name.split(':')[1] # extract only player formatted_player = player.split(':')[1] # extract only titles formatted_titles = int(titles.split(':')[1]) # extract only titles new_time = time.split(': ')[1] return f"{formatted_name} , {new_time}, {formatted_player} , {formatted_titles}" if __name__ == '__main__': report = 'Report: Daily_Report - Time: 2020-10-10T12:30:59.000000 - Player: Federer - Titles: 20 - Country: Switzerland' data = parse_function(report) print(f"Output \n{data}")
輸出
Daily_Report , 2020-10-10T12:30:59.000000, Federer , 20
6. 我們可以使用 parse 模組使其更簡單一些。正如您所看到的,該格式建立了一個模板。我們可以使用 parse 模組更輕鬆地做到這一點。
首先透過 - pip install parse 安裝 parse 模組。
from parse import parse report = 'Report: Daily_Report - Time: 2020-10-10T12:30:59.000000 - Player: Federer - Titles: 20 - Country: Switzerland' # Looking at the report, create a template template = 'Report: {name} - Time: {time} - Player: {player} - Titles: {titles} - Country: {country}' # Run parse and check the results data = parse(template, report) print(f"Output \n{data}")
輸出
<Result () {'name': 'Daily_Report', 'time': '2020-10-10T12:30:59.000000', 'player': 'Federer', 'titles': '20', 'country': 'Switzerland'}>
7. 透過簡單的單行程式碼,我們能夠透過定義模板從日誌中提取資料。現在讓我們提取各個值。
print(f"Output \n {data['name']} - {data['time']} - {data['player']} - {data['titles']} - {data['country']}")
輸出
Daily_Report - 2020-10-10T12:30:59.000000 - Federer - 20 - Switzerland
結論
您已經看到了幾種從日誌檔案中解析所需資料的方法。建議定義模板並使用 parse 模組提取所需資料。
廣告