这是我拥有的大型csv文件的一部分:
"66.35.223.128","66.35.223.143","1109647232","1109647247","AU","Australia"
"66.35.223.144","66.35.227.191","1109647248","1109648319","US","United States"
"66.35.227.192","66.35.227.207","1109648320","1109648335","JP","Japan"
"66.35.227.208","66.35.230.31","1109648336","1109648927","US","United States"
"66.35.230.32","66.35.230.47","1109648928","1109648943","AU","Australia"
"66.35.230.48","66.35.236.207","1109648944","1109650639","US","United States"
"66.35.236.208","66.35.236.223","1109650640","1109650655","AU","Australia"
"66.35.236.224","66.36.127.255","1109650656","1109688319","US","United States"
前两列是一系列IP地址。 我有一个IP地址66.35.250.168 我需要搜索csv文件以查看它所在的范围,并打印出相应的国家/地区名称。
由于前两个数字(66,35)相同,我打算搜索包含它的行。 我可以通过这样做来搜索完整的字符串(66.35.205.88):
import csv
with open('GeoIPCountryWhois.csv', mode='r') as f:
reader = csv.reader(f)
for row in reader:
if row[0] in ['66.35.205.88']:
print row
如果我搜索66.35,我没有得到任何结果。 你可以告诉我一种方法,我可以搜索字符串的一部分('66 .35'在这里)? 另外,你能告诉我如何找到我找到字符串的确切行号吗?
提前致谢。
答案 0 :(得分:4)
import csv
with open('GeoIPCountryWhois.csv', mode='r') as f:
reader = csv.reader(f)
for num, row in enumerate(reader):
if '66.35' in row[0]:
print num, row
请注意,如果'66.35'
出现在地址中的其他位置或该行的其他位置,则会出现误报。
编辑:这是一个可以实际检查它是否在正确范围内的版本。
def numeric_ip(ip):
return [int(x) for x in ip.split('.')]
desired_ip = numeric_ip('66.35.205.88')
with open('GeoIPCountryWhois.csv', mode='r') as f:
for num, row in enumerate(csv.reader(f)):
if numeric_ip(row[0]) <= desired_ip <= numeric_ip(row[1]):
print num, row
答案 1 :(得分:1)
没有理由in
不起作用。
确保切换订单
if '66.35' in row[0]:
print row
答案 2 :(得分:0)
您可以对字符串使用标准布尔测试来检查您要查找的ip是否在以下范围内:
import csv
desired_ip = "66.35.232.56"
desired_ip_n = [str(n) for n in desired_ip.split(".")
with open('GeoIPCountryWhois.csv', mode='r') as f:
reader = csv.reader(f)
row_num = 1
for row in reader:
ip_start_n = [str(n) for n in row[0].split(".")]
ip_end_n = [str(n) for n in row[1].split(".")]
if desired_ip_n >= ip_start_n and desired_ip <= ip_end_n:
print row
print row_num
row_num += 1