如何返回内部包含字符串的行,而不是匹配整个字符串?

时间:2018-07-03 00:12:41

标签: python

我将这段代码称为username/imagename

get.py

例如,当我运行import urllib2, base64, csv, sys from sys import argv request = urllib2.Request("https://example.com/test.csv") response = urllib2.urlopen(request) data = response.read() sheet = csv.read(data.split('\n'),delimiter=',') def main(): for row in sheet: if arg in row: print "Host"+row[5] + "IP"+row[6] if __name__ == "__main__": main() 时,我想获取其中包含./get.py 127的所有IP。

2 个答案:

答案 0 :(得分:1)

您当前正在检查字符串参数是否完全在列表中,而应该检查列表中 of 的特定元素(它似乎是索引6的元素):

import urllib2, base64, csv, sys
from sys import argv

request = urllib2.Request("https://example.com/test.csv")
response = urllib2.urlopen(request)
data = response.read()
sheet = csv.read(data.split('\n'),delimiter=',')

def main(arg):
    ip = arg[1]
    for row in sheet:
        if ip in row[6]:
            print("Host" + row[5] + "IP" + row[6])

if name == "main":
    main(argv)

答案 1 :(得分:0)

您可以尝试一下:

import urllib2, base64, csv, sys
from sys import argv

request = urllib2.Request("https://example.com/test.csv")
response = urllib2.urlopen(request)
data = response.read()
sheet = csv.reader(data.split('\n'), delimiter=',')

def main(arg):
    for row in sheet:
        if len(row) == 0:
            continue

        if arg in row[6]:
            print("Host" + row[5] + ", IP" + row[6])

if __name__ == "__main__":
    main(argv[1])

我使用python 2.7解释器尝试了此操作,并且似乎可以正常工作。