【问题标题】:Parse IP addresses from txt从 txt 解析 IP 地址
【发布时间】:2015-09-14 08:44:42
【问题描述】:

我正在尝试下载一个 txt 文件,您可以在该文件中找到 here。下载文件没问题:

    testfile = urllib.URLopener()
    testfile.retrieve(_proxy_list_download_, "proxies.txt")

但问题是下载时它的行为很奇怪。当我在任何 txt 编辑器中打开它时,我可以看到内容和 IP 地址,但是当我尝试将内容打印到控制台时,它会打印:

212.3.183.210:8080; 0; 0; anonymous proxy; Italy; ; a;  in); an Jose); ree download proxy IP

当我尝试从那里获取 IP 地址时,输出中没有地址。

with open('proxies.txt') as f:
            content = f.read()
            ip = re.findall( r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", content )

我已经尝试过另一个 regex:

r'([0-9]+)(?:\.[0-9]+){3}' 

这个regex只返回3位数字。

你知道如何解析这些 IP 吗?

编辑:这是来自文本编辑器的复制+粘贴文本,但在编辑器中,所有内容都在一行中:

 # http://proxy-ip-list.com/ provides you this fresh txt proxy list to free download proxy IP
# Date: Sat, 27 Jun 2015 12:53:02 +0000

39.166.95.9:8123; 0; 0; high-anonymous; China; 
178.189.92.118:3129; 16.83; 405; high-anonymous; Austria; 
198.2.202.33:8090; 8.05; 884; anonymous; United States (CA, San Jose); 
171.96.152.89:8080; 0; 0; anonymous; Thailand; 
153.149.104.76:80; 0; 0; anonymous; Japan (Tokyo); 
106.187.52.191:80; 0; 0; anonymous proxy; Japan; 
194.187.214.204:80; 0.91; 6374; anonymous proxy; Finland; 
59.78.160.247:8080; 0; 0; anonymous; China (Shanghai); 
61.156.3.166:80; 1.12; 1449; anonymous proxy; China (Jinan); 
221.238.140.164:8080; 1.39; 257; anonymous; China (Tianjin); 
117.178.157.107:8123; 8.44; 847; high-anonymous; China; 
39.166.205.95:8123; 0; 0; high-anonymous; China; 
117.163.216.8:8123; 4.21; 1577; high-anonymous; China; 
189.31.143.250:3128; 0; 0; high-anonymous; Brazil; 
183.89.84.82:8080; 0; 0; anonymous proxy; Thailand; 
183.88.41.42:8080; 0; 0; anonymous; Thailand; 
212.3.183.210:8080; 0; 0; anonymous proxy; Italy; 

【问题讨论】:

    标签: python regex parsing ip


    【解决方案1】:

    您需要删除锚点,因为一行不会只包含一个 IP 地址。

    ip = re.findall( r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", content )
    

    第二个正则表达式

    r'([0-9]+)(?:\.[0-9]+){3}' 
    

    必须返回三位数字,因为只有前三位数字被捕获,re.findall 方法将首先返回捕获(如果有)。如果没有捕获,则只有它会返回匹配项。通过将捕获组转换为非捕获组将为您提供所需的输出。

    r'\b[0-9]+(?:\.[0-9]+){3}\b' 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-06
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2014-10-11
      • 2010-09-27
      • 2023-04-07
      相关资源
      最近更新 更多