【问题标题】:How do I split between two hashes for desired output in Python如何在 Python 中拆分两个散列以获得所需的输出
【发布时间】:2023-03-05 20:49:01
【问题描述】:

首先,我想要此文件中所有唯一 IP 的列表。

这是我在 python 中读取的文件的一部分:

[node1] - 190.223.252.106 - 用户成功登录

[node2] - 239.84.157.20 - 用户成功上传个人资料图片

[node2] - 87.130.185.37 - 用户成功登录

[node6] - 210.155.211.219 - 用户支付成功

[node5] - 64.103.198.103 - 用户成功登录

我的代码:

def UniqueIP(fileparm):
counter = 0
input_file = open(fileparm, 'r')
file_contents = input_file.read()
input_file.close()
ip_list = file_contents.split()
unique_ip = set(ip_list)
for ip in unique_ip:
    counter += 1
    print(str(counter) + ': ' + str(ip) + "\n")

我有一个好的开始,但我的输出如下所示。我主要是获取 IP,但有时也会随机获取其余内容。我只想能够拆分“-”并仅获取 IP 作为输出。

29: 191.219.189.162

30: [节点3]

31: 21.147.6.59

32: 55.160.104.8

【问题讨论】:

    标签: python file hash split hyphen


    【解决方案1】:

    你需要遍历每一行:

    unique_ips = set()
    with open("path/to/file", "r", encoding="utf-8") as file:
      for line in file:
        line_parts = line.split("-", maxsplit=2)
        if len(line_parts) > 2:
          ip = line_parts[1]
          # Maybe you'd want to check if it's an IP here
          # if is_ip(ip):
          unique_ips.add(ip)
    

    然后你可以遍历集合

    for index, ip in enumerate(unique_ips):
      print(f"{index+1}: {ip}")
    

    在将 IP 添加到集合之前,我还要验证它实际上是一个 IP - 它正好有 4 个字节(0 到 255 之间),由一个点分隔:

    def is_ip(some_str):
      try:
        bvalues = list(map(int, some_str.split(".")))
      except ValueError:
        # Some of the stuff couldn't be parsed into int
        return False
      return all(0<=val<=255 for val in bvalues) and len(bvalues) == 4
    

    (请确保在其余代码之前声明此函数)

    【讨论】:

    • 为什么 unique_ips 未定义?
    • 因为我没有声明。我以您的代码为起点,并填写了缺少的内容。只需在使用前将其声明为空的set() 就可以了。在这一点上,如果你要声明 is_ip 函数,那么你需要弄清楚在哪里正确使用它,如果你要使用它。
    • 啊,好吧,是的,这行得通,谢谢你的帮助!加上额外的 IP 验证。
    【解决方案2】:

    如果行总是相同的,在该位置的 ip 地址前后都有一个-,那么您可以使用带有特定字符的split,选择适当的元素,然后将strip 删除多余的空格

    x = "node1] - 190.223.252.106 - User Successful Login"
    x.split('-')[1].strip()
    # 190.223.252.106
    

    但是,如果有更多变化,您最好使用正则表达式来专门匹配 IP 地址。

    【讨论】:

    • 是的,在 IP 之前/之后总是有“-”,但是如何将它添加到我当前的代码中?
    猜你喜欢
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多