-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_to_csv.py
More file actions
101 lines (80 loc) · 3.99 KB
/
convert_to_csv.py
File metadata and controls
101 lines (80 loc) · 3.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import json
import csv
import os
import re
from pathlib import Path
def clean_text(text):
"""Очищает текст от лишних символов и форматирования"""
if not text:
return ""
# Убираем лишние пробелы и специальные символы
text = re.sub(r'\s+', ' ', text).strip()
return text
def clean_rating(rating):
"""Очищает рейтинг от лишних точек"""
if not rating:
return ""
rating_str = str(rating)
# Убираем лишние точки в конце
rating_str = rating_str.rstrip('.')
return rating_str
def convert_cities_to_csv(ncity_folder="ncity", output_file="all_cities.csv"):
"""Конвертирует все JSON файлы городов в один CSV файл"""
# Получаем список всех JSON файлов в папке
ncity_path = Path(ncity_folder)
if not ncity_path.exists():
print(f"❌ Папка {ncity_folder} не найдена!")
return
json_files = list(ncity_path.glob("*.json"))
if not json_files:
print(f"❌ JSON файлы не найдены в папке {ncity_folder}")
return
print(f"Найдено {len(json_files)} JSON файлов")
# Создаем CSV файл
with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['city', 'name', 'rating', 'reviews', 'address', 'phone', 'website']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# Записываем заголовки
writer.writeheader()
total_organizations = 0
# Обрабатываем каждый файл города
for json_file in json_files:
# Извлекаем название города из имени файла
city_name = json_file.stem # получаем имя файла без расширения
print(f"Обрабатываем город: {city_name}")
try:
# Читаем JSON файл
with open(json_file, 'r', encoding='utf-8') as f:
organizations = json.load(f)
print(f" Найдено {len(organizations)} организаций")
# Обрабатываем каждую организацию
for org in organizations:
# Записываем строку в CSV
writer.writerow({
'city': city_name,
'name': clean_text(org.get('name', '')),
'rating': clean_rating(org.get('rating', '')),
'reviews': clean_text(str(org.get('reviews', ''))),
'address': clean_text(org.get('address', '')),
'phone': clean_text(org.get('phone', '')),
'website': clean_text(org.get('website', ''))
})
total_organizations += len(organizations)
except Exception as e:
print(f" ❌ Ошибка при обработке файла {json_file}: {e}")
continue
print(f"\n✅ Конвертация завершена!")
print(f"📁 Создан файл: {output_file}")
print(f"🏙️ Обработано городов: {len(json_files)}")
print(f"🏢 Общее количество организаций: {total_organizations}")
def main():
"""Основная функция"""
# Указываем папку с JSON файлами и имя выходного файла
ncity_folder = "ncity"
output_file = "all_cities.csv"
try:
convert_cities_to_csv(ncity_folder, output_file)
except Exception as e:
print(f"❌ Ошибка: {e}")
if __name__ == "__main__":
main()