2014-10-28 42 views
-1

我有一个文本文件,其中包含逗号分隔的IP数百个,它们之间只有空格。从python列表中分组ips

我需要一次拿10个,并把它们放在另一个代码块中。因此,对于IP地址:

1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, ... 123.123.123.123, 124.124.124.124, 125.125.125.125

我需要:

codethings [1.1.1.1, 2.2.2.2, ... 10.10.10.10] code code code 
codethings [11.11.11.11, 12.12.12.12, ... 20.20.20.20] code code code 
codethings [21.21.21.21, 22.22.22.22, ... 30.30.30.30] code code code 

etc 

我敢肯定,我可以用正则表达式做,但我不禁觉得有更简单的方法可以做到它。

任何及所有的帮助表示赞赏。谢谢!

+0

分割字符串,然后使用普通的切片,例如一个'=地图( str,range(50));打印[0:10]' – 2014-10-28 20:15:10

回答

0

上逗号分割,从每个元素带过多的空白:

txt = '''1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 
    123.123.123.123, 124.124.124.124, 125.125.125.125''' 

ip_list = map(str.strip, txt.split(',')) 

至于分页,请参阅答案:Paging python lists in slices of 4 itemsIs this how you paginate, or is there a better algorithm?

我也建议(只是要确定),以过滤掉无效的IP不会忽略,例如使用一台发电机和socket模块:上逗号

from __future__ import print_function 
import sys 
import socket 

txt = '''1.1.1.1, 2.2.2.2, 3.3.3.3, 4.4.4.4, 
    123.123.123.123, 124.124.124, 555.125.125.125,''' 

def iter_ips(txt): 
    for address in txt.split(','): 
     address = address.strip() 
     try: 
      _ = socket.inet_aton(address) 
      yield address 
     except socket.error as err: 
      print("invalid IP:", repr(address), file=sys.stderr) 

print(list(iter_ips(txt))) 
+0

是否可以使用文本文件本身,而不是将IP直接放入脚本中? (我目前无法尝试,但我很好奇......) 而不是 'txt ='''1.1.1.1,2.2.2.2,3.3.3.3,4.4.4.4, 123.123。 123.123,124.124.124,555.125.125.125,''''' do 'txt = open(“text.txt”)' ?? – rmp5s 2014-10-29 00:06:37