pip install geopy folium nltk
import folium
from geopy.geocoders import Nominatim
import nltk
import re
from nltk import word_tokenize, pos_tag, ne_chunk
from nltk.tree import Tree
nltk.download("punkt")
nltk.download("averaged_perceptron_tagger")
nltk.download("maxent_ne_chunker")
nltk.download("words")
def extract_locations(text):
"""
Extracts named entities (like countries/cities) using NLTK.
"""
locations = set()
tokens = word_tokenize(text)
pos_tags = pos_tag(tokens)
chunks = ne_chunk(pos_tags)
for chunk in chunks:
if isinstance(chunk, Tree) and chunk.label() == "GPE":
name = " ".join(c[0] for c in chunk.leaves())
locations.add(name)
return list(locations)
def geocode_locations(location_names):
"""
Uses geopy to convert place names into latitude and longitude.
"""
geolocator = Nominatim(user_agent="world_map_app")
geo_data = []
for name in location_names:
try:
location = geolocator.geocode(name)
if location:
geo_data.append({
"name": name,
"lat": location.latitude,
"lon": location.longitude
})
except Exception as e:
print(f"Geocoding error for {name}: {e}")
return geo_data
def create_world_map(locations):
"""
Create a world map using folium with markers on identified locations.
"""
m = folium.Map(location=[20, 0], zoom_start=2)
for loc in locations:
folium.Marker(
location=[loc["lat"], loc["lon"]],
popup=loc["name"],
icon=folium.Icon(color="blue", icon="info-sign")
).add_to(m)
m.save("world_map.html")
print("✅ Map saved to world_map.html")
# --------- MAIN FUNCTIONALITY ---------
if __name__ == "__main__":
print("Paste your text below (press Enter twice to end input):")
lines = []
while True:
line = input()
if line.strip() == "":
break
lines.append(line)
input_text = "\n".join(lines)
places = extract_locations(input_text)
print(f"📍 Places Found: {places}")
coords = geocode_locations(places)
create_world_map(coords)
No comments:
Post a Comment