亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 re 從 txt 文件制作字典

使用 re 從 txt 文件制作字典

慕哥6287543 2023-09-12 16:36:48
考慮 asset/logdata.txt 中的標準 Web 日志文件。該文件記錄用戶在訪問網頁時進行的訪問(就像這個!)。日志的每一行都有以下項目:主機(例如,'146.204.224.152')user_name(例如,'feest6811'注意:有時用戶名會丟失!在這種情況下,請使用“-”作為用戶名的值。)提出請求的時間(例如,'21/Jun/2019:15:45:24 -0700')post 請求類型(例如,'POST /incentivize HTTP/1.1'注意:并非所有內容都是 POST?。┠娜蝿帐菍⑵滢D換為字典列表,其中每個字典如下所示:example_dict = {"host":"146.204.224.152",                  "user_name":"feest6811",                  "time":"21/Jun/2019:15:45:24 -0700",                                 "request":"POST /incentivize HTTP/1.1"}這是 txt 數據文件的示例。我寫了這幾行代碼:import redef logs():    with open("assets/logdata.txt", "r") as file:        logdata = file.read()        #print(logdata)        pattern="""        (?P<host>.*)                (-\s)           (?P<user_name>\w*)          (\s)         ([POST]*)        (?P<time>\w*)                                """        for item in re.finditer(pattern,logdata,re.VERBOSE):            print(item.groupdict())        return(item)logs()它幫助我完成了任務"host","user_name"但是我無法繼續完成其余的要求。有人可以幫忙嗎?
查看完整描述

4 回答

?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

試試這個我的朋友


import re



def logs():

    logs = []

    w = '(?P<host>(?:\d+\.){3}\d+)\s+(?:\S+)\s+(?P<user_name>\S+)\s+\[(?P<time>[-+\w\s:/]+)\]\s+"(?P<request>.+?.+?)"'

    with open("assets/logdata.txt", "r") as f:

        logdata = f.read()

    for m in re.finditer(w, logdata):

        logs.append(m.groupdict())

    return logs


查看完整回答
反對 回復 2023-09-12
?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

請看下面的代碼:


import re


regex = re.compile(

    r'(?P<host>(?:\d+\.){1,3}\d+)\s+-\s+'

    r'(?P<user_name>[\w+\-]+)?\s+'

    r'\[(?P<time>[-\w\s:/]+)\]\s+'

    r'"(?P<request>\w+.+?)"'

)


def logs():

    data = []

    with open("assets/logdata.txt", "r") as f:

        logdata = f.read()

        for item in regex.finditer(logdata):

            x = item.groupdict()

            if x["user_name"] is None:

                x["user_name"] = "-"

            data.append(x)

    return data


logs()

請在下面找到輸出部分:


[{'host': '146.204.224.152', 'user_name': 'feest6811', 'time': '21/Jun/2019:15:45:24 -0700', 'request': 'POST /incentivize HTTP/ 1.1'}, {'主機': '197.109.77.178', '用戶名': 'kertzmann3129', '時間': '21/Jun/2019:15:45:25 -0700', '請求': '刪除/ virtual/solutions/target/web+services HTTP/2.0'}, {'host': '156.127.178.177', 'user_name': 'okuneva5222', 'time': '21/Jun/2019:15:45:27 -0700', '請求': '刪除/interactive/transparent/niches/revolutionize HTTP/1.1'}, {'主機': '100.32.205.59', '用戶名': 'ortiz8891', '時間': '21/ Jun/2019:15:45:28 -0700', 'request': 'PATCH /architectures HTTP/1.0'}, {'主機': '168.95.156.240', '用戶名': 'stark2413', '時間': '21/Jun/2019:15:45:31 -0700', '請求': 'GET /參與 HTTP/2.0'}, .....] 文本文件的每一行有 979 個字典。


查看完整回答
反對 回復 2023-09-12
?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

import re

def logs():

mydata = []

with open("assets/logdata.txt", "r") as file:

logdata = file.read()

pattern="""

(?P<host>.*)

(\s+)

(?:\S+)

(\s+)

(?P<user_name>\S+)

(\s+)

\[(?P<time>.*)\]\

(\s)

(?P<request>"(.)*")"""

for item in re.finditer(pattern,logdata,re.VERBOSE):

new_item = (item.groupdict())

mydata.append(new_item)

return(mydata)


查看完整回答
反對 回復 2023-09-12
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

您正在使用\wget?user_names,但\w不包括-可以在日志中的內容(通用日志格式(CLF)),因此您可以使用\S+(除空格之外的一個或多個任何內容)作為替代方案。對于time您可以創建一個捕獲組,僅允許該字段的預期字符(類)(例如\w\s-+時區、/日期和:時間)用方括號(文字)括起來,可以為request使用".


import re


regex = re.compile(

? ? r'(?P<host>(?:\d+\.){3}\d+)\s+'

? ? r'(?:\S+)\s+'

? ? r'(?P<user_name>\S+)\s+'

? ? r'\[(?P<time>[-+\w\s:/]+)\]\s+'

? ? r'"(?P<request>POST.+?)"'

)


def logs():

? ? data = []

? ? with open("sample.txt", "r") as f:

? ? ? ? logdata = f.read()

? ? for m in regex.finditer(logdata):

? ? ? ? data.append(m.groupdict())

? ? return data


print(logs())

(將第一行中的 user_name 替換為“-”以在第二行進行測試)


[

? ?{

? ? ? "host":"146.204.224.152",

? ? ? "user_name":"feest6811",

? ? ? "time":"21/Jun/2019:15:45:24 -0700",

? ? ? "request":"POST /incentivize HTTP/l.l"

? ?},

? ?{

? ? ? "host":"146.204.224.152",

? ? ? "user_name":"-",

? ? ? "time":"21/Jun/2019:15:45:24 -0700",

? ? ? "request":"POST /incentivize HTTP/l.l"

? ?},

? ?{

? ? ? "host":"144.23.247.108",

? ? ? "user_name":"auer7552",

? ? ? "time":"21/Jun/2019:15:45:35 -0700",

? ? ? "request":"POST /extensible/infrastructures/one-to-one/enterprise HTTP/l.l"

? ?},

? ? ...


查看完整回答
反對 回復 2023-09-12
  • 4 回答
  • 0 關注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號