python处理字符串(2)

来源:互联网 发布:java实现链表反转 编辑:程序博客网 时间:2024/06/14 20:26

如题


上次得到的ip格式是: 74.121.139.0 74.121.139.255 美国|0|0|0|0


那么这次为了构建树查询我们将用python将ip转换为这种格式:1 0 4&1 0 7*澳大利亚|0|0|0|0


就是将”.”和每段ip最后的字段去掉(ip最后的字段只是标示其为主机还是服务器,对其地理位置不产生影响)
代码在这儿

def main():    f = open("/home/wangjunx/Desktop/adre.txt", 'r')    a = open("/home/wangjunx/Desktop/ip.txt",'w')    linenum = 0    while linenum < 33116:        ip = f.readline()[:-1]#.decode("gb2312")        # print ip        point = ip        ip_start = ip[:ip.index(" ")]        # print "ip_start" ,"=", ip_start        ip_end = ip[ip.index(" ") + 1:ip.index(" ") + 1 + ip[ip.index(" ") + 1:].index(" ")]        # print " " in ip[ip.index(" ")+1:]        # print ip[ip.index(" ")+1:]        # print ip[ip.index(" ")+1:].index(" ")        # print "ip_end","=",ip_end        ip_address = ip[ip.index(" ") + 1 + ip[ip.index(" ") + 1:].index(" ") + 1:]        # print "ip_adress","=",ip_adress        ip_f = ip_start[:ip_start.index(".")]        # print ip_f        ip_s = ip_start[               ip_start.index(".") + 1: ip_start.index(".") + 1 + ip_start[ip_start.index(".") + 1:].index(".")]        # print ip_s        ip_start_re = ip_start[::-1]        ip_t = ip_start_re[               ip_start_re.index(".") + 1: ip_start_re.index(".") + 1 + ip_start_re[ip_start_re.index(".") + 1:].index(                   ".")][::-1]        # ip_t_false = ip_start[ip_start[ip_start.index(".")+1:].index(".")+1:] #xx.xx        # ip_t = ip_t_false[:ip_t_false.index(".")]        # print ip_t        ip_F = ip_end[:ip_end.index(".")]        # print ip_F        ip_S = ip_end[ip_end.index(".") + 1: ip_end.index(".") + 1 + ip_end[ip_end.index(".") + 1:].index(".")]        # print ip_S        ip_end_re = ip_end[::-1]        ip_T = ip_end_re[               ip_end_re.index(".") + 1: ip_end_re.index(".") + 1 + ip_end_re[ip_end_re.index(".") + 1:].index(".")][               ::-1]        # ip_T_false = ip_end[ip_end[ip_end.index(".") + 1:].index(".") + 1:]  # xx.xx        # ip_T = ip_T_false[:ip_T_false.index(".")]        # print ip_T        linenum = linenum + 1        ip_change = ip_f + " " + ip_s + " " + ip_t + "&" + ip_F + " " + ip_S + " " + ip_T + "*" + ip_address + "\n"        a.write(ip_change)    f.close()    a.close()if __name__ == '__main__':    main()

最近遇到些瓶颈。。。
有点儿难受。。。
希望能熬过去。。。

原创粉丝点击