0

我正在使用 ip2location 在名为 output.txt 的文件中查找 IP 地址列表的位置,并将答案写入另一个文件 ip_info.txt。我只想在我的文件中写入 IP 地址为 US 的条目。以下是我执行此操作的代码。

import IP2Location;
import urllib; 
import time;
start_time = time.time()
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("data/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE.BIN"); 
 t=open('ip_info','w');
 with open('output','r') as f: # file containing ip addresses
 for line_terminated in f:
     line= line_terminated.rstrip('\r\n'); # strip newline
     if line: # non-blank lines
        rec = IP2LocObj.get_all(line);
        if(rec.country_short == 'US')
           t.write(line);
           t.write('\t');
           t.write(rec.country_short);
           t.write('\n');
print("--- %s seconds ---" % (time.time() - start_time))

我在这里收到以下错误。

File "myprogram.py", line 13
if(rec.country_short == 'US')
SyntaxError: invalid syntax

作为参考,您可以查看https://www.ip2location.com/developers/python

4

2 回答 2

1

if(rec.country_short == 'US')不是有效的 Python。

你的意思:

if rec.country_short == 'US':?

于 2017-06-21T04:40:42.280 回答
0

所有代码

import IP2Location;
import urllib; 
import time;
start_time = time.time()
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("data/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE.BIN"); 
t=open('ip_info','w');
with open('output','r') as f:
     for line_terminated in f:
        line= line_terminated.rstrip('\r\n')
        if line:
          rec = IP2LocObj.get_all(line)
          if rec.country_short == 'US':
             t.write(line);
             t.write('\t');
             t.write(rec.country_short);
             t.write('\n');
print("--- %s seconds ---" % (time.time() - start_time))

你的意思是这样吗

于 2022-02-01T07:01:36.330 回答