【问题标题】:data from url open in list来自 url 的数据在列表中打开
【发布时间】:2015-01-07 11:09:14
【问题描述】:

我想从网上下载一个文件,即:http://www.malwaredomainlist.com/hostslist/ip.txt 并将其放入列表中以进一步操作列表中的项目。

我试过了

print "Downloading with urllib2"
    f = urllib2.urlopen(malwareurl)
    data = [f.read()]
    result = [stuff.replace("\r\n", "/32,") for stuff in data]
    print result
    print len([result])

列表本身“看起来”很好:

['100.42.50.110/32,103.14.120.121/32,.......']

但长度只有1.
我想我需要遍历 readlines 并在列表中为每个 readline 创建项目,对吗?

【问题讨论】:

  • 您只需对列表中的字符串使用 split 即可:result[0].split(',')

标签: python list urlopen


【解决方案1】:

我认为你过于复杂了:

print "Downloading with urllib2"
f = urllib2.urlopen(malwareurl)
ips = f.read().split("\r\n")

# If you want to add '/32' to each IP
ips = [x + "/32" for x in ips if x]

【讨论】:

  • 我尝试了result = f.read().split("\r\n"),结果“看起来”更好,但列表“结果”的长度仍然只有1
  • 尝试仅按\n分割
【解决方案2】:
>>> r=urllib2.urlopen('http://www.malwaredomainlist.com/hostslist/ip.txt')
>>> f=open('e.txt','w')
>>> ff=r.read()
>>> f.write(ff)
>>> f.close()

【讨论】:

    【解决方案3】:
    list1 = []
    print "Downloading with urllib2"
    f = urllib2.urlopen(malwareurl)
    ips = f.read()
    for ip in ips:
       ip = ip.strip()
       ip = ip + "/32"
       list1.append(ip)
    print list1
    print len(list1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多