def parse_udk(url, udk, parsed):
    def get_base_url(url):
        try:
            fname = url.split('/')[-1]
            return re.sub(fname, '', url)
        except IndexError:
            return url

    try:
        assert url not in parsed, (0, 'URL is parsed')
        parsed |= {url}

        base = get_base_url(url)

        teacode = BS(get(url).content, "lxml")
        assert teacode.find('h1').string.count('404') == 0, (404,
                                                             'Page not foud')
        x = teacode.find('tr')

        while 1:
            try:
                x = x.nextSibling
            except AttributeError:
                print(url, teacode, file=stderr)
                break
            try:
                strings = "".join([str(a) for a in x.contents])
                if strings.count('table') > 0:
                    break
            except AttributeError:
                pass

        table = x.find('table')

        for tr in table('tr'):
            try:
                proceed = 1
                code, value, _ = [c for c in tr('td')]
                assert re.match('\d', code.string), (1, 'No code in cell')
                url = base + code.find('a')['href'].strip('.')
            except AssertionError:
                proceed = 0
            except TypeError:
                url = ''
            except ValueError:
                proceed = 0
            except Exception as e:
                print(tr, file=stderr)
                proceed = 0
                raise e
            if proceed:
                udk.update({code.string: {'url': url, 'text': value.string}})
                dump(udk, 'udk.json', quiet=1)
                parse_udk(url, udk, parsed)

    except (AssertionError, MissingSchema) as e:
        print(url, e, file=stderr)
        pass
Example #2
0
def get_neighbors(region):
    def neighbors_from_a(pars):
        rez = []
        for p in pars:
            if  p.text.lower().count('граничит') > 0 or \
                p.text.lower().count('граница') > 0 or \
                p.text.lower().count('окружена') > 0:
                for a in p('a'):
                    try:
                        rez += [get_yandex_name(a['title'])]
                    except (KeyError, ValueError):
                        pass
        return rez

    def neighbors_from_text(pars):
        rez = []
        for p in pars:
            if  p.text.lower().count('граничит') > 0 or \
                p.text.lower().count('граница') > 0 or \
                p.text.lower().count('окружена') > 0:
                words = [
                    w for w in p.text.lower().split()
                    if not (w.startswith("област") or w.startswith("край")
                            or w.startswith("края") or w.startswith("респуб"))
                ]
                for word in words:
                    try:
                        print(word)
                        rez += [get_yandex_name(word)]
                    except ValueError:
                        pass
        return rez

    try:
        return regions[region]['neighbors']
    except KeyError:
        try:
            soup = BS(get('https://ru.wikipedia.org/wiki/%s' %
                          region.replace(' ', '_')).content,
                      features="lxml")
            neighbor_candidates = neighbors_from_a(soup('p'))
            assert len(neighbor_candidates) > 1, 'Не найдены ссылки'
        except AssertionError:
            neighbor_candidates = neighbors_from_text(soup('p'))

        neighbor_candidates = set(neighbor_candidates)
        same = {region}
        print(same, neighbor_candidates)
        neighbors = list(regnames & neighbor_candidates - same)
        regions[region].update({'neighbors': neighbors})
        dump(regions, 'regions.json', quiet=1)
        return neighbors
Example #3
0
def start_recording(lidar, fname):
    try:
        open(LOCK, 'w').write(now())
        out = []
        for new_scan, quality, φ, ρ in lidar.iter_measurments():
            out += [(time(), new_scan, quality, φ, ρ)]
            if len(out) > 100000:
                dump(object=out, filename=fname % now())
                out = []
                if not isfile(LOCK):
                    break
    except Exception as e:
        raise e
Example #4
0
def get_distance_adi(reg_A, reg_B):
    try:
        return distances['%s<->%s' % (reg_A, reg_B)]
    except KeyError:
        try:
            center_A = get_wiki_center(reg_A).replace(' ', '+')
            center_B = get_wiki_center(reg_B).replace(' ', '+')
            soup = BS(
                get('https://www.avtodispetcher.ru/distance/?from=%s&to=%s' %
                    (center_A, center_B)).content,
                features='lxml')
            d = int(soup.find(id="totalDistance").text)
        except AttributeError:
            d = 10000
        except ValueError:
            raise ValueError
        distances.update({'%s<->%s' % (reg_A, reg_B): d})
        distances.update({'%s<->%s' % (reg_B, reg_A): d})
        dump(distances, 'distances.json', quiet=1)
        return get_distance_adi(reg_A, reg_B)
Example #5
0
def get_distance_rdt(reg_A, reg_B):
    try:
        return distances['%s<->%s' % (reg_A, reg_B)]
    except KeyError:
        try:
            center_A = get_wiki_center(reg_A).replace(' ', '+')
            center_B = get_wiki_center(reg_B).replace(' ', '+')
            soup = BS(get('https://ru.distance.to/%s/%s' %
                          (center_A, center_B)).content,
                      features='lxml')
            d = int(
                soup.find('span', "value km").text.replace('.', '').replace(
                    ',', '')) * 1.3 // 100
        except AttributeError:
            d = 10000
        except ValueError:
            raise ValueError
        distances.update({'%s<->%s' % (reg_A, reg_B): d})
        distances.update({'%s<->%s' % (reg_B, reg_A): d})
        dump(distances, 'distances.json', quiet=1)
        return get_distance_rdt(reg_A, reg_B)
Example #6
0
from glob import glob
from rutermextract import TermExtractor as TE
from utilites import dump
import re

te = TE()

_out = {}
for txt in glob('txt/*'):
    reg = re.findall(r'.*/(.*)\..*', txt)[0]
    terms = te(open(txt).read(), strings=1)
    _out.update({reg: terms})

dump(_out, 'out.json')
Example #7
0
from glob import glob
from nltk.tokenize import WordPunctTokenizer as WPT
from utilites import dump, compare

import re

wpt = WPT()

words = []
for txt in glob('txt/*'):
    words += [
        x for x in wpt.tokenize(open(txt).read())
        if len(x) > 3 and not re.findall(r'\d+|[a-z]+|\W+|_+', x)
    ]

ngrams = {}

for n in [2, 3, 4, 5]:
    for i in range(len(words)):
        x = words[i:n + i]
        if len(set(x)) == n:
            ngram = " ".join(x)
        try:
            ngrams[ngram] += 1
        except KeyError:
            ngrams.update({ngram: 1})

ngrams = sorted((x for x in ngrams.items() if x[1] > 2), key=lambda x: x[1])

dump(ngrams, 'ngrams.json')
Example #8
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in1 = load('jsondb/трансформированные данные.json')
_in2 = load('jsondb/avg_std.json')

регионы = list(_in1.keys())
показатели = list(_in1[регионы[0]].keys())

data = np.zeros([len(показатели), len(регионы)])

rez = {}
for регион in регионы:
    poka = {}
    for показатель in показатели:
        try:
            показатель.index('%')
            x = (_in1[регион][показатель])
            poka.update({показатель: x})
        except ValueError:
            x = (_in1[регион][показатель] -
                 _in2[показатель]['avg']) / _in2[показатель]['std']
            poka.update({показатель: x})
    rez.update({регион: poka})

dump(rez, 'jsondb/нормированные данные.json')
Example #9
0
from utilites import load, dump

def stage_1(_in):
    rez = {}
    for reg in _in.keys():
        B = _in[reg]['Численность раб.силы (тыс. человек)']
        C = _in[reg]['с высшим образование от раб.силы %'] #
        D = _in[reg]['Численность безработных (тыс. человек)']
        E = _in[reg]['с высшим образованием от безработных %']
        Количество_людей_с_высшим_образованием = (B / 100) * C + (D / 100) * E #Расчет количества людей с высшим образованием 

        rez.update({reg:Количество_людей_с_высшим_образованием})
    return rez

if __name__ == '__main__':
    _in = load('jsondb/количество людей с ВО.json')
    _out = stage_1(_in)
    dump(_out, 'jsondb/Количество людей с высшим образованием из числа занятых и безработных.json')
Example #10
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in0 = load('jsondb/нормированные данные.json')
_in1 = load('jsondb/вес показателей.json')

регионы = list(_in0.keys())
показатели = list(_in0[регионы[0]].keys())
эталонный_регион = "Пермский край"

rez = {}
for эталонный_регион in регионы:
    row = {}
    for регион in регионы:
        _sum = 0
        for показатель in показатели:
            try:
                вес = _in1[показатель]
                показатель_эт_региона = _in0[эталонный_регион][показатель]
                показатель_региона = _in0[регион][показатель]
                x = вес * ((показатель_эт_региона - показатель_региона)**2)
                _sum += x
            except KeyError:
                pass
            row.update({регион: _sum})
    rez.update({эталонный_регион: row})

dump(rez, 'jsondb/матрица для экселя.json')
Example #11
0
res = {}
# print(codes)
for r in r_data:
    # print(r)
    try:
        neighbors = reg[r_data[r]["emissname"]]
        print(neighbors)
        key = r
    except KeyError:
        try:
            neighbors = reg[r_data[r]["yandexname"]]
            key = r_data[r]["yandexname"]
        except KeyError:
            key = [
                x for x in reg.keys()
                if compare(x, r_data[r]["emissname"]) >= 0.65
            ][0]
            neighbors = reg[key]
    code_neighbors = []
    for n in neighbors:
        code_neighbors += [(codes[n], neighbors[n])]
    res.update({
        key: {
            "neighbors": sorted(code_neighbors, key=lambda x: x[1]),
            "code": r_data[r]["code"]
        }
    })

dump(res, 'r_data.json', 1)
Example #12
0
from xlrd import open_workbook, cellname
from utilites import load, dump

wb = open_workbook('xlsxdb/data.xlsx')

ws = wb.sheet_by_name('Расчет кол-ва людей с ВО')

rez = {}
for row in range(1, 86):
    reg = ws.cell(row, 0).value.replace('\n', ' ').strip()
    data = {}
    for col in range(1, 5):
        cat = ws.cell(0, col).value.replace('\n', ' ').strip()
        v = ws.cell(row, col).value
        data.update({cat: v})
    rez.update({reg: data})

dump(rez, 'jsondb/количество людей с ВО.json')
Example #13
0
    row = []
    for x in range(ws.ncols):
        row += [ws.cell(y, x).value.replace('\n', ' ').strip()]
    categories += [row]

rez = {}
subcat, cat = '', ''
for n in range(len(categories[2])):
    subsubcat = categories[2][n]
    if subsubcat:
        if categories[1][n]:
            subcat = categories[1][n]
        if categories[0][n]:
            cat = categories[0][n]
        rez.update({subsubcat: (subcat, cat)})

dump(rez, 'jsondb/categories.json')

rez = {}
for row in range(3, 88):
    data = {}
    for col in range(1, ws.ncols):
        reg = ws.cell(row, 0).value.replace('\n', ' ').replace(' – ',
                                                               ' - ').strip()
        subsubcat = ws.cell(2, col).value.replace('\n', ' ').strip()
        v = ws.cell(row, col).value
        data.update({subsubcat: v})
    rez.update({reg: data})

dump(rez, 'jsondb/исходные данные.json')
Example #14
0
                row.update({mat.capitalize(): 1 - idx})
                found = 1
        if not found:
            row.update({mat.capitalize(): 0})

    data.update({reg_a: row})

for reg in data.keys():
    x = 0
    n = 0
    for mat in data[reg].keys():
        x += data[reg][mat]
        n += 1
    x = x / n
    data[reg].update({'avg': x})
dump(data, 'test2.json')

with open('out.csv', 'w') as csv:
    csv.write('\t')
    for mat in data["Российская Федерация"].keys():
        csv.write('"%s"\t' % mat)
    csv.write('\n')

    for reg in data.keys():
        csv.write('"%s"\t' % reg)
        for mat in data[reg].keys():
            csv.write('%s\t' % str(data[reg][mat]).replace('.', ','))
        csv.write('\n')

#with open("%s.csv" % mat, "w") as f:
#    for idx, reg in sorted(data):
Example #15
0
from utilites import load, dump

_in = load('jsondb/секторная структура.json')


def stage_2(_in):
    rez = {}
    for reg in _in.keys():
        data = {}
        for _pok in _in[reg].keys():
            A = _in[reg][_pok][
                'ВРП']  #ВРП по основным видам экономической деятельности
            B = _in[reg][_pok][
                'ЧИСЛ']  #Среднегодовая численность занятых по основным видам экономической деятельности
            X = A / (
                B * 1000
            )  #Расчет производительности труда по основным видам экономической деятельности

            data.update({_pok: X})

        rez.update({reg: data})
    return rez


if __name__ == '__main__':
    _in = load('jsondb/секторная структура.json')
    _out = stage_2(_in)
    dump(_out, 'jsondb/Производительность труда.json')
Example #16
0
            filtered_data = load('filtered_data.json')
            structured_data = load('structured_data.json')
            clusters = load('clusters.json')
            spec_data = load('spec_data.json')

            calculated_sums = load('calculated_sums.json')
            calculated_lq = load('calculated_lq.json')
            distances = load('distances.json')
            cluster_hi_lo = load('cluster_hi_lo.json')
            neib_regions = load('neib_regions.json')
            region_colors = load('region_colors.json')
            end = True
        except FileNotFoundError as e:
            if e.filename == 'fedstat_data.json':
                fedstat_data = download_fedstat()
                dump(fedstat_data, 'fedstat_data.json')
            if e.filename == 'filtered_data.json':
                filtered_data = filter_fedstat(fedstat_data['results'])
                dump(list(filtered_data), 'filtered_data.json')
            if e.filename == 'structured_data.json':
                structured_data = make_structure(filtered_data)
                dump(structured_data, 'structured_data.json')
            if e.filename == 'clusters.json':
                clusters = clusters_from_dot()
                dump(clusters, 'clusters.json')
            if e.filename == 'spec_data.json':
                spec_data = make_spec_data(structured_data['По регионам'], clusters)
                dump(spec_data, 'spec_data.json')
            if e.filename == 'calculated_sums.json':
                calculated_sums = calc_sums(spec_data)
                dump(calculated_sums, 'calculated_sums.json')
Example #17
0
import numpy as np
import scipy as sp

_in = load('jsondb/трансформированные данные.json')

регионы = list(_in.keys())
показатели = list(_in[регионы[0]].keys())

data = np.zeros([len(показатели), len(регионы)])

x = 0
for регион in регионы:
    y = 0
    for показатель in показатели:
        data[y, x] = _in[регион][показатель]
        y += 1
    x += 1

rez = {}
i = 0
for показатель in показатели:
    rez.update(
        {показатель: {
            'avg': np.average(data[i]),
            'std': np.std(data[i])
        }})
    i += 1

dump(rez, 'jsondb/avg_std.json')
from rutermextract import TermExtractor
from bs4 import BeautifulSoup
from utilites import dump
from get_intuit_sentences import get_normal_form

te = TermExtractor()

try:
    word_normal_form = load('word_normal_form.json')
except FileNotFoundError:
    word_normal_form = {}

text = BeautifulSoup(open('lection.html').read(), 'lxml').text
terms = te(text)
terms = [([get_normal_form(x) for x in str(term).split()], term.count)
         for term in terms if str(term).count(' ') > 1]
dump(terms, 'intuit_terms.json')
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 18 12:21:02 2019

@author: dan
"""
from utilites import load, dump
from rutermextract import TermExtractor as TE
from sys import stderr

to_del = set()
udk = load('udk.json')

for code, value in [(k, udk[k]['text']) for k in udk.keys()]:
    if value:
        terms = [t.normalized for t in TE()(value)]
        data = udk[code]
        data.update({'terms': terms})
        udk.update({code: data})
        print(code, terms, file=stderr)
    else:
        to_del |= {code}

for code in to_del:
    udk.pop(code)

dump(udk, 'indexed.udk.json')
Example #20
0
from xlrd import open_workbook, cellname
from utilites import load, dump

wb = open_workbook('xlsxdb/data.xlsx')

ws = wb.sheet_by_name('Расчет производительности')

rez = {}
for row in range(3, 88):
    reg = ws.cell(row, 0).value.replace('\n', ' ').strip()
    data = {}
    for col in range(1, 14):
        key1 = ws.cell(2, col).value.replace('\n', ' ').strip()
        v1 = ws.cell(row, col).value
        v2 = ws.cell(row, col + 14).value
        data.update({key1: {'ЧИСЛ': v1, 'ВРП': v2}})
    rez.update({reg: data})

dump(rez, 'jsondb/секторная структура.json')

#        cat = ws.cell(0, col).value.replace('\n', ' ').strip()
#        v = ws.cell(row, col).value
#        data.update({cat:v})
#    rez.update({reg:data})

#
Example #21
0
n = 0
for sentence in [re.sub(r"\n+|\s+", " ", x) for x in pst.tokenize(text)]:
    sent_tokens = list(
        set([get_normal_form(t) for t in wpt.tokenize(sentence)]))
    tokens = [t for t in sent_tokens if is_word(t)]
    Q = len(tokens) / len(sent_tokens)
    x = {
        n: {
            "tokens": tokens,
            "sentence": sentence,
            "Q": Q,
            "len": len(tokens),
        }
    }
    sentences.update(x)
    n += 1
Q = np.array([sentences[s]['Q'] for s in sentences])
L = np.array([sentences[s]['len'] for s in sentences])

q_min, q_max = Q.mean() - Q.std(), Q.mean() + Q.std()
l_min, l_max = L.mean() - L.std(), L.mean() + L.std()

sentences = {
    i: sentences[i]
    for i in sentences if q_min <= sentences[i]['Q'] <= q_max
    and l_min <= sentences[i]['len'] <= l_max
}

dump(sentences, 'intuit_sents.json')
dump(word_normal_form, 'word_normal_form.json')
dump(list(stop_words), 'stop_words.json')
Example #22
0
0.08	Государственное управление и обеспечение военной безопасности; социальное обеспечение	государтсвенное управление	государственный аппарат	военная безопасность	социальное обеспечение	инфраструктура																										
0.42	Образование	Образование дошкольное	Образование начальное общее	Образование основное общее	Образование профессиональное	школа	вуз	университет	институт	Образование высшее	бакалавриат	магистратура	специалитет	Образование дополнительное																		
0.33	Деятельность в области здравоохранения и социальных услуг	здравоохранение	медицина	социальные услуги	больница	врач	стационар	лечение	пациент																							
0.25	Деятельность в области культуры, спорта, организации досуга и развлечений	культура	спорт	искусство	развлечения	библиотеки	архивы	музеи	отдых																							"""

#_instr = """0.67	Строительство	Строительство зданий	Строительство инженерных сооружений	Работы строительные специализированные	жилищное строительство	строительство																										"""

metrix = [x.split('\t')[1:] for x in _instr.lower().split('\n')]
weight = [float(x.split('\t')[0]) for x in _instr.lower().split('\n')]

rez = {}
for mat in metrix:
    row = {}
    for reg in regions.keys():
        L = len(regions[reg])
        i = 0
        found = []
        for term in regions[reg]:
            for var in mat:
                dx = compare(var, term.lower()) if var else 0
                if dx > 0.6999:
                    found += [[term, 1 - (i / L), dx]]
            i += 1
        if found:
            pos = np.average([_[1] for _ in found])
            row.update({reg: pos})

    rez.update({mat[0]: row})

dump(rez, 'test1.json')
Example #23
0
@author: dan
"""
import re
from utilites import dump, load
from rutermextract import TermExtractor as TE                       
te = TE()

res = {}
subres = {}
for line in [ a.strip('\n') for a in load('specs.json'):
    try:
        m = re.match(r'[А-Я]+', line)
        if m.group() == line.split()[0]:
            name = line.capitalize().strip()
            try:
                res.update({oldname:subres})
                oldname = name
            except NameError:
                oldname = name
            subres = {}
        else:
            a = [ str(a) for a in te(line) ]
#            nname = ' и '.join(a[:2]).capitalize()
            nname = line.capitalize().strip()
            subres.update({nname:a})
    except AttributeError:
        pass
  
  
dump(object=res, filename='specs.json')
Example #24
0
        port = '/dev/ttyUSB%s' % n
        print('Searchin RPLidar on port %s ... ' % port, end = '', flush = 1)
        lidar = RPLidar(port)
        lidar.connect()
        print('done')
        break
    except RPLidarException:
        print('fail!')

out = []
for new_scan, quality, φ, ρ in lidar.iter_measurments():
    out += [(new_scan, quality, φ, ρ)]
    if len(out) > 1000:
        break
    
dump(out, 'scan.json')

raise Exception

def normalize(layer):
    rez = []
    for φ0 in range(360):
        Δφ_min = 360
        out = ()
        for z, φ, ρ in layer:
            Δφ = abs(φ -φ0) 
            if Δφ < Δφ_min:
                out = (z, φ0, ρ)
                Δφ_min = Δφ
        rez += [out]
    return rez
Example #25
0
    candidates = sorted(candidates, key=lambda x: x[1], reverse=1)
    
    text = open('text.csv','w')
    used = []
    tokens = candidates[0][2]
    for pos, q, tags in candidates:
        if q > 0:
            i = pos
            s = sentences[str(i)]
            if i not in used:
                text.write("%s ^ %s ^ %s\n" % (s['sentence'], i, q))
                used += [i]
    
    text.close()
    text = sorted(text, key=lambda x: x[1])
    dump(text, 'text.json')
    
out = BeautifulSoup("<body/>","lxml")
p = out.new_tag('p')
new = 1
for sentence, n in text:
    try:
        p.string += sentence
    except TypeError:
        p.string = sentence
    if np.random.choice(10) > 8:
        out.body.insert(len(out('p')),p)
        p = out.new_tag('p')

out.body.insert(len(out('p')),p)
open('/tmp/out.html', 'w').write(out.prettify())
Example #26
0
        for n in [1,2,3,4]:
            скос_i = sp.stats.skew(data[i_показатель] ** (1/n), 0, 0)
            скосы += [(abs(скос_i), n)]
        
        n = min(скосы)[1]
        data[i_показатель] = data[i_показатель] ** (1/n)
        
скос = sp.stats.skew(data, 1, 0)

rez = {}
i = 0
for показатель in показатели:
    rez.update({показатель:скос[i]})
    i += 1

dump(rez, 'jsondb/скос new.json')

for i_показатель in показатели:
    print(round(скос0[i_показатель],2), round(rez[i_показатель], 2), i_показатель)
    
rez = {}
x = 0
for регион in регионы:
    y = 0
    pok = {}
    for показатель in показатели:
        pok.update({показатель:data[y,x]})
        y += 1
    rez.update({регион:pok})
    x += 1
Example #27
0
import numpy as np
import scipy as sp

_in0 = load('jsondb/нормированные данные.json')
_in1 = load('jsondb/вес показателей.json')

регионы = list(_in0.keys())
показатели = list(_in0[регионы[0]].keys())
эталонный_регион = "Пермский край"

rez = {}
for эталонный_регион in регионы:
    row = {}
    for регион in регионы:
        if (эталонный_регион != регион):
            _sum = 0
            for показатель in показатели:
                try:
                    вес = _in1[показатель]
                    показатель_эт_региона = _in0[эталонный_регион][показатель]
                    показатель_региона = _in0[регион][показатель]
                    x = вес * ((показатель_эт_региона - показатель_региона)**2)
                    _sum += x
                except KeyError:
                    pass
            row.update({регион: _sum})
    rez.update({эталонный_регион: row})

dump(rez, 'jsondb/матрица структурных расстояний.json')
Example #28
0
from utilites import load, dump

def stage_3(_in1, _in2, _in3):
    for reg in _in2.keys():
        x = _in1[reg]
        _in2[reg]["Количество людей с высшим образованием из числа занятых и безработных (тыс.человек)"] = x
        for k in _in3[reg].keys():
            _in2[reg][k] = _in3[reg][k]
    return _in2

if __name__ == '__main__':
    _in1 = load('jsondb/Количество людей с высшим образованием из числа занятых и безработных.json')
    _in2 = load('jsondb/исходные данные.json')
    _in3 = load('jsondb/Производительность труда.json')
    _out = stage_3(_in1, _in2, _in3)  
    dump(_out, 'jsondb/исходные данные (ред).json')
Example #29
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in = load('jsondb/исходные данные (ред).json')

регионы = list(_in.keys())
показатели = list(_in[регионы[0]].keys())

data = np.zeros([len(регионы), len(показатели)])

x = 0
for регион in регионы:
    y = 0
    for показатель in показатели:
        data[x, y] = _in[регион][показатель]
        y += 1
    x += 1

скос = sp.stats.skew(data, 0, 0)

rez = {}
i = 0
for показатель in показатели:
    rez.update({показатель: скос[i]})
    i += 1

dump(rez, 'jsondb/скос.json')
Example #30
0
from utilites import load, dump

import numpy as np
import scipy as sp

_in0 = load('jsondb/нормированные данные.json')
_in1 = load('jsondb/вес показателей.json')

регионы = list(_in0.keys())
показатели = list(_in0[регионы[0]].keys())
эталонный_регион = "Пермский край"

rez = {}
for регион in регионы:
    _sum = 0
    for показатель in показатели:
        try:
            вес = _in1[показатель]
            показатель_эт_региона = _in0[эталонный_регион][показатель]
            показатель_региона = _in0[регион][показатель]
            x = вес * ((показатель_эт_региона - показатель_региона)**2)
            _sum += x
        except KeyError:
            pass
    rez.update({регион: _sum})

dump(rez, 'jsondb/индекс структурного расстояния.json')