推 wadd: 謝謝前輩指點,又學到很多招 01/20 03:41
※ 引述《cuteSquirrel (可愛的小松鼠)》之銘言:
: https://pastebin.com/XAfGA0iY
: import urllib.request
: url = "https://admin.quic.cloud/api/dnslist"
: contents = urllib.request.urlopen(url).read().decode('utf-8')
: # 得到每一行
: str_contents = contents.splitlines()
: # 用網頁上的 空白 短槓 空白 切割每一行
: parsing = lambda s:s.split(' - ')
: # DNS_dict: python dictionary
: # DNS名字當作 key
: # IP位置當作 value
: DNS_dict = dict( [ *map(parsing, str_contents) ] )
: print( DNS_dict )
: ======================================================
: 各位前輩好。
: 下面的程式碼可以執行
: 但我總得感覺起來沒有利落的感覺
: 好像用任何程式語言都可以寫出類似的東西
: 可以請前輩指點一二。
: 希望將網頁的結果轉成單純的 temp dict
: import urllib.request
: url = "https://admin.quic.cloud/api/dnslist"
: contents = urllib.request.urlopen(url).read().decode('utf-8')
: str_contents = contents.split('\n')
: temp = dict()
: for i in str_contents:
: if i == '':
: continue
: cdn, ip = i.split(' - ')
: temp[cdn] = ip
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.13.182 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1670033854.A.A5E.html
再補充
1. 用Comprehension,可與map, filter比較
d = {k: v for k, v in (L.split(' - ') for L in contents.splitlines() if L)}
----------------------------------------------------------------------------
2. 用re
資料來源的羅列呈現方式可能會變,屆時分段或分隔符的邏輯就又要改
但最重要的資料本身,格式變動機率就小很多,如DNS,IP
所以用re主動抓幾乎不會變的格式,未來邏輯改寫機率低
另一好處是其他人看code也知道要的是什麼
(分段分隔只能知道資料的組織方式,但無法知道資料是甚麼,較為被動)
import re
regex_DNS = '-'.join(['[a-zA-Z]+']*4+['[0-9]+'])
regex_IP = '.'.join(['[0-9]{1,3}']*4)
regex_DNS_IP = '('+regex_DNS+').*?('+regex_IP+')'
d1 = dict(zip(re.findall(regex_DNS, contents), re.findall(regex_IP, contents)))
d2 = dict(re.findall(regex_DNS_IP, contents))
assert d1 == d2