python处理字符串(2)

如题


上次得到的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()

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值