[Python] 纯文本查看 复制代码
import tkinter as tk
from tkinter import messagebox, scrolledtext, filedialog
import pandas as pd
import requests
import json
def search_poi(keyword, city, api_key, page_size=25, max_pages=100):
url = "http://restapi.amap.com/v3/place/text"
all_pois = []
seen = set()
offset = 0
try:
for page in range(1, max_pages + 1):
params = {
'key': api_key,
'keywords': keyword,
'city': city,
'output': 'json',
'extensions': 'all',
'offset': offset,
'limit': page_size
}
response = requests.get(url, params=params)
response.raise_for_status()
result = response.json()
if result['status'] != '1':
if 'INVALID_USER_KEY' in result['info']:
raise ValueError("无效的API密钥,请检查您的密钥设置。")
else:
raise ValueError(result['info'])
# 将每个POI的名称和地址组合成元组,用于去重
for poi in result.get('pois', []):
poi_tuple = (poi['name'], poi['address'])
if poi_tuple not in seen:
seen.add(poi_tuple)
all_pois.append(poi)
if not result.get('pois'):
break
offset += page_size
except requests.RequestException as e:
messagebox.showerror("网络错误", f"网络请求失败: {e}")
except ValueError as ve:
messagebox.showerror("错误", str(ve))
except Exception as e:
messagebox.showerror("未知错误", str(e))
return all_pois
def on_search_button_click():
keyword = entry_keyword.get()
city = entry_city.get()
if not keyword or not city:
messagebox.showerror("错误", "请填写关键字和城市!")
return
try:
pois = search_poi(keyword, city, api_key)
if pois:
display_pois(pois)
update_counts(pois)
else:
messagebox.showinfo("提示", "未找到匹配的POI信息。")
except Exception as e:
messagebox.showerror("错误", str(e))
def display_pois(pois):
text_widget.delete('1.0', tk.END)
text_widget.insert(tk.END, "网点名称\t地址\n")
for poi in pois:
text_widget.insert(tk.END, f"{poi['name']}\t{poi['address']}\n")
def update_counts(pois):
# 初始化计数器
counts = {'中国石油': 0, '中国石化': 0, '兵团石油': 0, '其他': 0}
# 遍历POI列表进行计数
for poi in pois:
name = poi.get('name', '').strip()
if '中国石油' in name:
counts['中国石油'] += 1
elif '中国石化' in name:
counts['中国石化'] += 1
elif '兵团石油' in name:
counts['兵团石油'] += 1
else:
counts['其他'] += 1
total_count = sum(counts.values())
label_total.config(text=f"总共搜索到 {total_count} 条数据")
label_china_oil.config(text=f"{counts['中国石油']}")
label_china_petrochemical.config(text=f"{counts['中国石化']}")
label_bingtuan_oil.config(text=f"{counts['兵团石油']}")
label_other.config(text=f" {counts['其他']}")
def on_export_button_click():
poi_list = text_widget.get("1.0", tk.END).splitlines()[2:] # 跳过标题行
poi_data = [line.split('\t') for line in poi_list if line.strip()]
if poi_data:
df = pd.DataFrame(poi_data, columns=['网点名称', '地址'])
file_path = filedialog.asksaveasfilename(defaultextension=".xlsx")
if file_path:
df.to_excel(file_path, index=False)
messagebox.showinfo("成功", "导出完成!")
else:
messagebox.showinfo("取消", "导出操作被取消。")
else:
messagebox.showerror("错误", "没有数据可以导出。")
api_key = "XXXXXXXXXXXXXXX"
root = tk.Tk()
root.geometry("800x600+630+80")
root.title("加油站POI搜索")
frame_search = tk.Frame(root)
frame_search.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
label_keyword = tk.Label(frame_search, text="关键字:")
label_keyword.pack(side=tk.LEFT)
entry_keyword = tk.Entry(frame_search, width=20)
entry_keyword.pack(side=tk.LEFT, padx=(0, 5))
label_city = tk.Label(frame_search, text="城市:")
label_city.pack(side=tk.LEFT, padx=(5, 0))
entry_city = tk.Entry(frame_search, width=20)
entry_city.pack(side=tk.LEFT)
search_button = tk.Button(frame_search, text="搜索POI", command=on_search_button_click)
search_button.pack(side=tk.LEFT, padx=5)
export_button = tk.Button(frame_search, text="导出到Excel", command=on_export_button_click)
export_button.pack(side=tk.LEFT, padx=5)
frame_results = tk.Frame(root)
frame_results.pack(fill=tk.BOTH, expand=True)
scrollbar = tk.Scrollbar(frame_results)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
text_widget = scrolledtext.ScrolledText(frame_results, wrap=tk.WORD, width=40, height=10, yscrollcommand=scrollbar.set)
text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=text_widget.yview)
frame_counts = tk.Frame(frame_results)
frame_counts.pack(side=tk.BOTTOM, fill=tk.X, padx=5, pady=5)
label_total = tk.Label(frame_counts, text="")
label_total.pack(side=tk.LEFT)
tk.Label(frame_counts, text="中国石油: ").pack(side=tk.LEFT, padx=5)
label_china_oil = tk.Label(frame_counts, text="")
label_china_oil.pack(side=tk.LEFT)
tk.Label(frame_counts, text="中国石化: ").pack(side=tk.LEFT, padx=5)
label_china_petrochemical = tk.Label(frame_counts, text="")
label_china_petrochemical.pack(side=tk.LEFT)
tk.Label(frame_counts, text="兵团石油: ").pack(side=tk.LEFT, padx=5)
label_bingtuan_oil = tk.Label(frame_counts, text="")
label_bingtuan_oil.pack(side=tk.LEFT)
tk.Label(frame_counts, text="其他: ").pack(side=tk.LEFT, padx=5)
label_other = tk.Label(frame_counts, text="")
label_other.pack(side=tk.LEFT)
root.mainloop()