簡體   English   中英

如何以可讀的形式打印此列表?

[英]How do i print this list in a readable form?

我編寫了一個簡短的python腳本來搜索日志文件中帶有http狀態代碼的URL。 該腳本按預期工作,並計算結合某個http狀態代碼請求URL的頻率。 帶有結果的字典未分類。 這就是我之后使用字典中的值對數據進行排序的原因。 這部分腳本按預期工作,我得到一個帶有網址和計數器的排序列表,該列表如下所示:

([('http://example1.com"', 1), ('http://example2.com"', 5), ('http://example3.com"', 10)])

我只想讓它更易讀,並在行中打印列表。

http://example1.com      1  
http://example2.com      5  
http://example3.com      10  

我在兩周前開始使用python,但我找不到解決方案。 我嘗試了幾個在stackoverflow上找到的解決方案,但沒有任何效果。 我當前的解決方案以單獨的行打印所有網址,但不顯示計數。 我不能使用逗號作為分隔符,因為我的日志文件中有一些帶逗號的URL。 對不起我的英語不好和愚蠢的問題。 先感謝您。

from operator import itemgetter
from collections import OrderedDict

d=dict()

with open("access.log", "r") as f:
    for line in f:
        line_split = line.split()
        list = line_split[5], line_split[8]
        url=line_split[8]
        string='407'
        if string in line_split[5]:
            if url in d:
                d[url]+=1
            else:
                d[url]=1


sorted_d = OrderedDict(sorted(d.items(), key=itemgetter(1)))

for element in sorted_d:
    parts=element.split(') ')
    print(parts)
for url, count in sorted_d.items():
    print(f'{url} {count}')

用上面的替換你的最后一個for循環。

解釋一下:我們解壓縮url,在for循環中計算sorted_d中的對,然后使用f-string打印url並用空格分隔計數。

首先,如果您已經從collections庫中導入,為什么不導入Counter

from collections import Counter

d=Counter()

with open("access.log", "r") as f:
    for line in f:
        line_split = line.split()
        list = line_split[5], line_split[8]
        url=line_split[8]
        string='407'
        if string in line_split[5]:
            d[url] += 1

for key, value in d.most_common():  # or reversed(d.most_common())
    print(f'{key} {value}')

有關於如何格式化在Python字符串,如許多好的教程

這里是一個如何打印字典的示例代碼。 我用變量c1c2設置列的寬度。

c1 = 34; c2 = 10 
printstr = '\n|%s|%s|' % ('-'*c1, '-'*c2)
for key in sorted(d.keys()):
    val_str = str(d[key])
    printstr += '\n|%s|%s|' % (str(key).ljust(c1), val_str.rjust(c2))
printstr += '\n|%s|%s|\n\n' % ('-' * c1, '-' * c2)
print(printstr)

字符串函數ljust()創建一個作為參數傳遞的長度的字符串,其中字符串的內容是左對齊的。

暫無
暫無

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

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