gpt4 book ai didi

python - 将文本文件的行添加到字典

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:44 25 4
gpt4 key购买 nike

我一直在努力思考我将如何做到这一点,但我似乎无所适从。

如果我有一个文本文件,其中包含主机名及其相应的 IP 地址:

The result of www.espn.com is 199.181.133.15
The result of www.espn.com is 199.454.152.10
The result of www.espn.com is 20.254.215.14
The result of www.google.com is 141.254.15.14
The result of www.google.com is 172.14.54.153
The result of www.yahoo.com is 181.145.254.12

如何在列表或字典中获取地址及其对应的 ip 地址?

所以像 www.google.com 会是这样的:

("www.google.com", 141.254.15.14, 172.14.54.153)

上面的行将始终采用相同的格式,因此我可以遍历文件,采用上面的代码,使用 split(),并将地址添加到字典中。

  ....... 
....
dictA = {}
for line in f:
splitLine = line.split()
dictA = {splitLine[2]: splitLine[3]}

键只是网站,值是其所有对应的 ip 地址。我只需要将它们放在一个列表中或放在一起。

最佳答案

您可以使用 collections 中的 defaultdict 并将默认值设置为列表:

>>> from collections import defaultdict
>>> s = '''The result of www.espn.com is 199.181.133.15
... The result of www.espn.com is 199.454.152.10
... The result of www.espn.com is 20.254.215.14
... The result of www.google.com is 141.254.15.14
... The result of www.google.com is 172.14.54.153
... The result of www.yahoo.com is 181.145.254.12'''.splitlines()
>>> dictA = defaultdict(list)
>>> for line in s:
... words = line.split()
... dictA[words[3]].append(words[-1])
...
>>> dictA
defaultdict(<type 'list'>, {'www.yahoo.com': ['181.145.254.12'], 'www.espn.com': ['199.181.133.15', '199.454.152.10', '20.254.215.14'], 'www.google.com': ['141.254.15.14', '172.14.54.153']})

>>> for key, val in dictA.items():
... print key, val
...
www.yahoo.com ['181.145.254.12']
www.espn.com ['199.181.133.15', '199.454.152.10', '20.254.215.14']
www.google.com ['141.254.15.14', '172.14.54.153']

关于python - 将文本文件的行添加到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com