使用python将txt文件中的ip地址转换成当地城市名称
具体代码
import re
import requests
import concurrent.futures
# 用于匹配IPv4地址的正则表达式
ipv4_pattern = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b')
# 用于发送API请求并获取城市信息的函数
def get_city_info(ip):
response = requests.get(f'http://ip-api.com/json/{ip}')
data = response.json()
return data['city'] if data['status'] == 'success' else ip
# 读取文件内容
with open('result.txt', 'r') as file:
content = file.read()
# 使用正则表达式查找所有IPv4地址
ip_addresses = re.findall(ipv4_pattern, content)
# 使用多线程并行处理IP地址查询
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
city_results = list(executor.map(get_city_info, ip_addresses))
# 替换IPv4地址为城市信息
for old_ip, new_city in zip(ip_addresses, city_results):
content = content.replace(old_ip, new_city)
# 将修改后的内容写回文件
with open('result3.txt', 'w') as file:
file.write(content)
就能将ip地址转换成拼音格式啦(不是中文哈~)!!!