151100
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def clear_string_values(data):
|
||||
"""
|
||||
Рекурсивно очищает все строковые значения, оставляя только пустые кавычки (""),
|
||||
не изменяя значения None или другие типы данных.
|
||||
"""
|
||||
if isinstance(data, str):
|
||||
return ""
|
||||
elif isinstance(data, list):
|
||||
return [clear_string_values(item) for item in data]
|
||||
elif isinstance(data, dict):
|
||||
return {key: clear_string_values(value) for key, value in data.items()}
|
||||
return data
|
||||
|
||||
|
||||
def process_json_file(file_path):
|
||||
"""
|
||||
Обрабатывает указанный JSON-файл, очищая строковые значения, и сохраняет результат
|
||||
в новый файл с суффиксом '_cleared'.
|
||||
"""
|
||||
with open(file_path, 'r', encoding='utf-8') as file:
|
||||
data = json.load(file)
|
||||
|
||||
# Очищаем все строковые значения
|
||||
cleared_data = clear_string_values(data)
|
||||
|
||||
# Сохраняем результат в новый файл с суффиксом '_cleared'
|
||||
new_file_path = f"{os.path.splitext(file_path)[0]}_cleared.json"
|
||||
with open(new_file_path, 'w', encoding='utf-8') as new_file:
|
||||
json.dump(cleared_data, new_file, ensure_ascii=False, indent=4)
|
||||
|
||||
print(f"Файл с очищенными данными сохранен как: {new_file_path}")
|
||||
|
||||
|
||||
# Укажите путь к вашему JSON-файлу
|
||||
file_path = 'E:\code\kvant.app\FS_primer.json'
|
||||
process_json_file(file_path)
|
||||
@@ -0,0 +1,55 @@
|
||||
import json
|
||||
|
||||
|
||||
# Загрузка данных о регионах из внешнего JSON
|
||||
def load_region_data(data_file="regions_data.json"):
|
||||
try:
|
||||
with open(data_file, "r", encoding="utf-8") as f:
|
||||
return json.load(f).get("regions", [])
|
||||
except FileNotFoundError:
|
||||
print(f"Файл {data_file} не найден.")
|
||||
return []
|
||||
|
||||
|
||||
# Функция для добавления городов в GeoJSON
|
||||
def add_cities_to_geojson(input_geojson="russia_2.geojson", output_geojson="updated_russia_2.geojson"):
|
||||
# Загрузка исходного GeoJSON файла
|
||||
with open(input_geojson, "r", encoding="utf-8") as f:
|
||||
geo_data = json.load(f)
|
||||
|
||||
# Загрузка данных о регионах
|
||||
region_data = load_region_data()
|
||||
region_map = {region["id"]: region for region in region_data}
|
||||
|
||||
for feature in geo_data.get("features", []):
|
||||
# Обработка данных региона
|
||||
region_id = feature["properties"].get("id")
|
||||
region_info = region_map.get(region_id, {})
|
||||
|
||||
# Добавление информации о главном городе
|
||||
major_city = region_info.get("major_cities", None)
|
||||
if major_city:
|
||||
# Примерные координаты (замените на реальные для каждого города, если они известны)
|
||||
city_coords = [[-100.0, 60.0]] # Заглушка, замените на реальные координаты для каждого города
|
||||
city_feature = {
|
||||
"type": "Feature",
|
||||
"geometry": {
|
||||
"type": "Point",
|
||||
"coordinates": city_coords
|
||||
},
|
||||
"properties": {
|
||||
"name": major_city,
|
||||
"region_id": region_id
|
||||
}
|
||||
}
|
||||
# Добавляем город в список фич
|
||||
geo_data["features"].append(city_feature)
|
||||
|
||||
# Запись обновленного GeoJSON файла
|
||||
with open(output_geojson, "w", encoding="utf-8") as f:
|
||||
json.dump(geo_data, f, ensure_ascii=False, indent=4)
|
||||
print(f"Файл обновлен и сохранен как {output_geojson}")
|
||||
|
||||
|
||||
# Запуск функции
|
||||
add_cities_to_geojson()
|
||||
@@ -0,0 +1,55 @@
|
||||
import os
|
||||
import json
|
||||
|
||||
def decode_text(text):
|
||||
"""
|
||||
Преобразует строки с ошибкой кодировки из Latin-1 в UTF-8.
|
||||
"""
|
||||
try:
|
||||
return text.encode('latin1').decode('utf-8')
|
||||
except (UnicodeEncodeError, UnicodeDecodeError):
|
||||
return text
|
||||
|
||||
def recursive_decode(obj):
|
||||
"""
|
||||
Рекурсивно декодирует строки в объекте JSON.
|
||||
"""
|
||||
if isinstance(obj, str):
|
||||
return decode_text(obj)
|
||||
elif isinstance(obj, list):
|
||||
return [recursive_decode(item) for item in obj]
|
||||
elif isinstance(obj, dict):
|
||||
return {key: recursive_decode(value) for key, value in obj.items()}
|
||||
return obj
|
||||
|
||||
def process_json_file(file_path):
|
||||
"""
|
||||
Обрабатывает JSON-файл, декодируя строки с ошибочной кодировкой Latin-1.
|
||||
Создает новый файл с суффиксом '_decoded'.
|
||||
"""
|
||||
with open(file_path, 'r', encoding='utf-8') as file:
|
||||
data = json.load(file)
|
||||
|
||||
# Рекурсивно декодируем все строки в JSON-структуре
|
||||
decoded_data = recursive_decode(data)
|
||||
|
||||
# Создаем новый файл с суффиксом '_decoded'
|
||||
new_file_path = f"{os.path.splitext(file_path)[0]}_decoded.json"
|
||||
with open(new_file_path, 'w', encoding='utf-8') as new_file:
|
||||
json.dump(decoded_data, new_file, ensure_ascii=False, indent=4)
|
||||
print(f"Создан файл: {new_file_path}")
|
||||
|
||||
def process_directory(directory_path):
|
||||
"""
|
||||
Рекурсивно обрабатывает все JSON-файлы в указанной директории.
|
||||
"""
|
||||
for root, _, files in os.walk(directory_path):
|
||||
for file_name in files:
|
||||
if file_name.endswith('.json'):
|
||||
file_path = os.path.join(root, file_name)
|
||||
print(f"Обработка файла: {file_path}")
|
||||
process_json_file(file_path)
|
||||
|
||||
# Укажите путь к папке с JSON-файлами
|
||||
directory_path = 'E:\code\kvant.app'
|
||||
process_directory(directory_path)
|
||||
+47
-4
@@ -5,14 +5,57 @@ with open('russia.geojson', 'r', encoding='utf-8') as infile:
|
||||
data = json.load(infile)
|
||||
|
||||
# Поля, которые нужно оставить
|
||||
fields_to_keep = ['id', 'name', 'full_name', 'major_cities', '_cartodb_id0', 'cartodb_id']
|
||||
fields_to_keep = ['id', 'name', '_cartodb_id0', 'cartodb_id']
|
||||
|
||||
# Обновляем свойства в каждом объекте features
|
||||
|
||||
# Функция для округления координат до 3 знаков после запятой
|
||||
def round_coordinates(coords):
|
||||
if isinstance(coords[0], list):
|
||||
# Обработка вложенных списков (для MultiPolygon или других сложных структур)
|
||||
return [round_coordinates(c) for c in coords]
|
||||
else:
|
||||
# Округление координат точки
|
||||
return [round(coord, 3) for coord in coords]
|
||||
|
||||
|
||||
# Функция для удаления дубликатов из списка координат на самом нижнем уровне вложенности
|
||||
def remove_duplicate_coordinates(coords):
|
||||
if not all(isinstance(c, list) and len(c) == 3 for c in coords):
|
||||
# Если это не список пар координат (lon, lat), пропускаем обработку
|
||||
return coords
|
||||
|
||||
seen = set()
|
||||
unique_coords = []
|
||||
for coord in coords:
|
||||
coord_tuple = tuple(coord) # Преобразуем список координат в кортеж для использования в множестве
|
||||
if coord_tuple not in seen:
|
||||
seen.add(coord_tuple)
|
||||
unique_coords.append(coord)
|
||||
return unique_coords
|
||||
|
||||
|
||||
# Обновляем свойства, округляем и удаляем дубликаты координат в каждом объекте features
|
||||
for feature in data['features']:
|
||||
# Сжатие свойств
|
||||
feature['properties'] = {key: feature['properties'][key] for key in fields_to_keep if key in feature['properties']}
|
||||
|
||||
# Запись резФультата в новый файл
|
||||
# Округление координат
|
||||
rounded_coords = round_coordinates(feature['geometry']['coordinates'])
|
||||
|
||||
# Удаление дубликатов для координатных структур (обрабатываем только нижний уровень)
|
||||
if feature['geometry']['type'] == 'Point':
|
||||
# Для точки просто округляем координаты
|
||||
feature['geometry']['coordinates'] = rounded_coords
|
||||
elif feature['geometry']['type'] in ['Polygon', 'MultiLineString']:
|
||||
# Удаляем дубликаты на уровне списков координат (например, [[lon, lat], [lon, lat], ...])
|
||||
feature['geometry']['coordinates'] = [remove_duplicate_coordinates(part) for part in rounded_coords]
|
||||
elif feature['geometry']['type'] == 'MultiPolygon':
|
||||
# Удаляем дубликаты в многоуровневых структурах (например, [[[lon, lat], [lon, lat], ...], ...])
|
||||
feature['geometry']['coordinates'] = [[remove_duplicate_coordinates(part) for part in polygon] for polygon in
|
||||
rounded_coords]
|
||||
|
||||
# Запись результата в новый файл
|
||||
with open('russia_2.geojson', 'w', encoding='utf-8') as outfile:
|
||||
json.dump(data, outfile, ensure_ascii=False, separators=(',', ':'))
|
||||
|
||||
print("Обработка завершена. Результат записан в output.json.")
|
||||
print("Обработка завершена. Результат записан в russia_2.geojson.")
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import json
|
||||
|
||||
# Чтение данных из файла
|
||||
with open('regions_data.json', 'r', encoding='utf-8') as infile:
|
||||
data = json.load(infile)
|
||||
|
||||
# Функция для заполнения пустых полей
|
||||
def fill_missing_data(region):
|
||||
fields = ["population", "square", "additionalInfo"]
|
||||
for field in fields:
|
||||
if field not in region or region[field] in [None, ""]:
|
||||
region[field] = "" # Заполняем пустым значением
|
||||
return region
|
||||
|
||||
# Обработка данных регионов
|
||||
data['regions'] = [fill_missing_data(region) for region in data['regions']]
|
||||
data['regions'].sort(key=lambda x: x['id']) # Сортировка регионов по id
|
||||
|
||||
# Обработка данных городов
|
||||
data['cities'] = [fill_missing_data(city) for city in data.get('cities', [])]
|
||||
data['cities'].sort(key=lambda x: x['id']) # Сортировка городов по id
|
||||
|
||||
# Запись обновленных данных в файл
|
||||
with open('sorted_regions_data.json', 'w', encoding='utf-8') as outfile:
|
||||
json.dump(data, outfile, ensure_ascii=False, indent=2)
|
||||
|
||||
print("Обработка завершена. Данные отсортированы и записаны в sorted_regions_data.json")
|
||||
+2639319
-1
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user