帮我用python写一个程序,从格式为“确诊病例8-10:居住于东西湖区汉江康居二期8栋。”的txt文本中提取确诊病例的居住地点,并用高德API转换为经纬度,导出到excel文件中
时间: 2024-06-03 22:10:02 浏览: 66
好的,我会帮您写这个程序。
import re
import requests
import json
import xlwt
# 读取txt文本内容
with open("病例信息.txt", "r", encoding="utf-8") as f:
content = f.read()
# 正则表达式提取居住地点
pattern = r"确诊病例\d+-\d+:居住于([\u4e00-\u9fa5]+)"
result = re.findall(pattern, content)
# 高德API转换地址为经纬度
api_key = "your_api_key" # 替换为您的API Key
url = "https://restapi.amap.com/v3/geocode/geo?address="
locations = []
for address in result:
try:
response = requests.get(url+address+"&key="+api_key)
json_data = json.loads(response.text)
location = json_data["geocodes"][0]["location"]
locations.append(location)
except:
locations.append("无法获取经纬度")
# 导出到excel
workbook = xlwt.Workbook(encoding="utf-8")
worksheet = workbook.add_sheet("居住地点")
worksheet.write(0, 0, "居住地点")
worksheet.write(0, 1, "经度")
worksheet.write(0, 2, "纬度")
for i in range(len(result)):
worksheet.write(i+1, 0, result[i])
if locations[i] != "无法获取经纬度":
worksheet.write(i+1, 1, locations[i].split(",")[0])
worksheet.write(i+1, 2, locations[i].split(",")[1])
else:
worksheet.write(i+1, 1, locations[i])
worksheet.write(i+1, 2, locations[i])
workbook.save("居住地点.xls")
希望这个程序能够满足您的需求,如有问题可以随时咨询我。
阅读全文