我正在用python编写代码来解析流文件中的跟踪器信息。
import bencoder
import sys
target = './'+sys.argv[1]
with open(target, 'rb') as torrent_file:
torrent = bencoder.decode(torrent_file.read())
i=0
while True:
try:
print(torrent[b'announce-list'][i])
i+=1
except:
break输出如下。
b'udp://tracker.openbittorrent.com:80/announce‘
B‘’udp://tracker.opentry ackr.org:1337/announce‘
我想在下面的表单中解析这个值。
"tracker.openbittorrent.com",80
"tracker.opentrackr.org",1337年
我应该如何解析它?
发布于 2022-01-26 11:23:51
为此,可以使用urllib.parse.urlparse,如下所示
from urllib.parse import urlparse
url1 = b'udp://tracker.openbittorrent.com:80/announce'
url2 = b'udp://tracker.opentrackr.org:1337/announce'
c1 = urlparse(url1)
c2 = urlparse(url2)
hostport1 = c1.netloc.rsplit(b':',1)
hostport2 = c2.netloc.rsplit(b':',2)
hostport1[0] = hostport1[0].decode()
hostport1[1] = int(hostport1[1])
hostport2[0] = hostport2[0].decode()
hostport2[1] = int(hostport2[1])
print(hostport1)
print(hostport2)输出
['tracker.openbittorrent.com', 80]
['tracker.opentrackr.org', 1337]说明:我提取netloc,然后从右b':'最多拆分一次,然后应用.decode到主机端口将bytes转换为str,int将bytes转换为int。
编辑:经过更仔细的阅读,我注意到您可能会访问.hostname和.port,它们允许更简洁的代码来完成该任务,即
from urllib.parse import urlparse
url1 = b'udp://tracker.openbittorrent.com:80/announce'
url2 = b'udp://tracker.opentrackr.org:1337/announce'
c1 = urlparse(url1)
c2 = urlparse(url2)
hostport1 = [c1.hostname.decode(), c1.port]
hostport2 = [c2.hostname.decode(), c2.port]
print(hostport1)
print(hostport2)提供与上面代码相同的输出。
https://stackoverflow.com/questions/70862501
复制相似问题