簡體   English   中英

如何使用 pandas 從 .log 文件中讀取數據

[英]How to read data from .log file with pandas

我有一個日志文件,其中包含來自 webscrape 腳本的 100 頁數據。 .log 文件在日志中讀取如下:

Title: Canon EF 100mm f/2.8L Macro IS USM
Price: 6�900 kr
Link: https://www.finn.no/bap/forsale/ad.html?finnkode=161065896
21-Oct-19 10:21:14 - Found:
Title: Canon EF 100mm f/2.8L Macro IS USM
Price: 7�500 kr
Link: https://www.finn.no/bap/forsale/ad.html?finnkode=155541389
21-Oct-19 10:21:14 - Found:
Title: Panasonic Lumix G 25mm F1.4 ASPH
Price: 3�200 kr
Link: https://www.finn.no/bap/forsale/ad.html?finnkode=161066674

我想導入這些數據並將其發送到 excel 之類的

title           price      link
canon 100mm     6900kr     https

如果日志文件不是您顯示的順序,則需要更改方法。 如以下 function 將始終開始查找標題、價格和鏈接文本並添加到列表中。 要轉換為 dataframe,所有列表的長度必須相等。 讓我知道它是否有效。

def log_to_frame(location="./datalake/file.log"):
    with open(location, mode='r', encoding='UTF-8') as f:
        title_list = []
        price_list = []
        link_list = []
        for line in f:
            if "Title" in line:
                title = line.split(": ")[1].rstrip()
                title_list.append(title)
            elif "Price" in line:
                price = line.split(": ")[1].replace("�", "").rstrip()
                price_list.append(title)
            elif "Link" in line:
                link = line.split(": ")[1].rstrip()
                link_list.append(title)
            else:
                pass
    main_df = pd.DataFrame({"title": title_list, "price": price_list, "link": link_list})
    return main_df


log_df = log_to_frame()
log_df.to_excel("log.xlsx", index=False)

您可以將數據作為普通表加載到 DataFrame 中,然后使用 DataFrame 的logreset_index函數組合列。 這假設每一行只有一個“:”符號,將“鍵”列與“值”列分開,並且每個“記錄”對於每個鍵都有一行。

import pandas as pd

p = pd.read_table("table.log", sep=':', header=None)
df = pd.DataFrame()
keys = set(p[0]) # set of all unique keys

for key in keys:
  # get all values with the current key and re-index them from 0...n
  col_data = p.loc[p[0]==key][1].reset_index(drop=True)
  # put this in a new column named after the key
  df[key] = col_data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM