Advertisement
BERKYT

csv-create-graph

Nov 12th, 2021 (edited)
1,637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.15 KB | None | 0 0
  1. # ----------------------------------------------------------------------------------------------------------------------
  2.  
  3. # Python-модуль для построения графиков на основе csv-файлов.
  4.  
  5. # ----------------------------------------------------------------------------------------------------------------------
  6. import matplotlib.pyplot as plt
  7. import csv
  8. import os
  9.  
  10. plt.rcParams["figure.figsize"] = (7,5)
  11.  
  12. def count_file_in_folder(path, str_in_file_name):
  13.     """
  14.    Подсчитывает кол - во файлов в директории.
  15.  
  16.    :param path:
  17.        Путь до директории, где мы проверяем кол - во файлов.
  18.    :param str_in_file_name:
  19.        Строка, которая должна содержаться в имени файла.
  20.    :return:
  21.        Возвращает кол - во таких файлов в директории.
  22.    """
  23.  
  24.     str_in_file_name, count_file = str(str_in_file_name), 0
  25.     for i in range(len(os.listdir(path))):
  26.         if str_in_file_name in str(os.listdir(path)[i]):
  27.             count_file += 1
  28.  
  29.     return count_file + 1
  30.  
  31.  
  32. def convert_date_to_time(list_date):
  33.     """
  34.    Преобразовывает дату во время.
  35.  
  36.    :param list_date:
  37.        Строка с датой прохождения теста.
  38.    :return:
  39.        Возвращает список списков ЧЧ.ММ.СС.МСМС.
  40.    """
  41.  
  42.     list_result = []
  43.  
  44.     for date_tmp in list_date:
  45.         if date_tmp == '__EMPTY__':
  46.             list_result.append([date_tmp])
  47.             continue
  48.         str_tmp = ''
  49.         flag = False
  50.  
  51.         for char in date_tmp:
  52.             if flag:
  53.                 if char.isdigit():
  54.                     str_tmp += char
  55.                 else:
  56.                     str_tmp += '_&&_'
  57.             elif char == 'T':
  58.                 flag = True
  59.  
  60.         list_result.append(str_tmp.split('_&&_')[:-1])
  61.  
  62.     print(list_result, file=open('list_result.txt', 'a'))
  63.  
  64.     if not list_result:
  65.         return None
  66.     else:
  67.         return list_result
  68.  
  69.  
  70. def arithmetic_sum(path, question, response):
  71.     """
  72.    Вычисляет общее время ответа на вопрос.
  73.  
  74.    :param path:
  75.        Путь до файла.
  76.    :param question:
  77.        Ключ вопроса.
  78.    :param response:
  79.        Ключ ответа.
  80.    :return:
  81.        Возвращает общее время ответа на вопрос.
  82.    """
  83.  
  84.     with open(path) as f:
  85.         list_keys = str(f.readline()).replace('"', '').split(',')
  86.  
  87.     list_keys = list_keys[1:]
  88.  
  89.     with open(path) as f:
  90.         reader = csv.DictReader(f)
  91.         dict_reader_tmp = {}
  92.         for i in range(len(list_keys)):
  93.             dict_reader_tmp[list_keys[i]] = []
  94.  
  95.         for row in reader:
  96.             for i in range(len(list_keys)):
  97.                 if question in list_keys[i] or response in list_keys[i]:
  98.                     if row[list_keys[i]] == '':
  99.                         dict_reader_tmp[list_keys[i]].append('__EMPTY__')
  100.                     else:
  101.                         dict_reader_tmp[list_keys[i]].append(row[list_keys[i]])
  102.  
  103.     dict_reader = {}
  104.     dict_reader_cleared = {}
  105.     for i in range(len(list_keys)):
  106.         dict_reader[list_keys[i]] = []
  107.  
  108.     for key in dict_reader.keys():
  109.         dict_reader[key] = convert_date_to_time(dict_reader_tmp[key])
  110.  
  111.     list_keys.clear()
  112.     for key in dict_reader.keys():
  113.         if dict_reader[key] is not None:
  114.             list_keys.append(key)
  115.             dict_reader_cleared[key] = dict_reader[key]
  116.  
  117.     dif = difference(dict_reader_cleared)
  118.     # print('arithmetic_mean = ', sum(dif) / len(dif))
  119.     return sum(dif)
  120.  
  121.  
  122. def convert_str_to_int(list_from):
  123.     """
  124.    Конвертирует список строк в список чисел.
  125.  
  126.    :param list_from:
  127.        Принимает список строк.
  128.    :return:
  129.        Возвращает результирующий список.
  130.    """
  131.  
  132.     list_int_converted = []
  133.     for element in list_from:
  134.         if element == '__EMPTY__':
  135.             list_int_converted.append(element)
  136.             continue
  137.         list_int_converted.append(int(element))
  138.  
  139.     return list_int_converted
  140.  
  141.  
  142. def sum_time(list_time):
  143.     """
  144.    Сумма времени ответов на вопросы.
  145.  
  146.    :param list_time:
  147.        Принимает список с данными по времени на каждый вопрос.
  148.    :return:
  149.        Возвращает сумму, в виде кортежа, времени ответов на вопросы и индексы где, была пустая строка.
  150.    """
  151.  
  152.     result = []
  153.     list_pop_index = []
  154.  
  155.     for (offset, element) in enumerate(list_time):
  156.         if '__EMPTY__' in element:
  157.             list_pop_index.append(offset)
  158.             result.append('__EMPTY__')
  159.             continue
  160.         else:
  161.             result.append((element[0] * ((60 ** 2) * 1000)) + (element[1] * (60 * 1000))
  162.                           + (element[2] * 1000) + element[3])
  163.  
  164.     return result, list_pop_index
  165.  
  166.  
  167. def difference(dict_date):
  168.     """
  169.    Находит разность времени начала и конца ответа на вопросы.
  170.  
  171.    :param dict_date:
  172.        Принимает словарь времени начала и конца ответа на вопросы.
  173.    :return:
  174.        Возвращает разность времени начала и конца ответа на вопросы.
  175.    """
  176.  
  177.     list_result_question = []
  178.     list_result_response = []
  179.  
  180.     for (offset, key) in enumerate(dict_date):
  181.         if offset % 2 == 0:
  182.             for i in range(len(dict_date[key])):
  183.                 list_result_question.append(convert_str_to_int(dict_date[key][i]))
  184.         else:
  185.             for i in range(len(dict_date[key])):
  186.                 list_result_response.append(convert_str_to_int(dict_date[key][i]))
  187.  
  188.     result_question_tmp = sum_time(list_result_question)
  189.     result_response_tmp = sum_time(list_result_response)
  190.  
  191.     list_result_difference = []
  192.  
  193.     for tuple_of_elements in zip(result_response_tmp[0], result_question_tmp[0]):
  194.         if tuple_of_elements[0] == '__EMPTY__':
  195.             continue
  196.         elif tuple_of_elements[1] == '__EMPTY__':
  197.             continue
  198.         else:
  199.             list_result_difference.append(tuple_of_elements[0] - tuple_of_elements[1])
  200.  
  201.     return list_result_difference
  202.  
  203.  
  204. def graph(path_to_csv_file, type_test, len_test, write_result='off'):
  205.     """
  206.    Строит график по запросу.
  207.  
  208.    :param path_to_csv_file:
  209.        Путь до папки с csv-файлами.
  210.    :param type_test:
  211.        Тип теста.
  212.    :param len_test:
  213.        Длина теста.
  214.    :param write_result:
  215.        Нужно ли выводить процесс работы функции на экран(не график, а именно процесс работы.).
  216.    :return:
  217.        Ничего не возвращает.
  218.    """
  219.  
  220.     if write_result != 'on' and write_result != 'off':
  221.         print('invalid arg!')
  222.         return
  223.  
  224.     dict_result_tmp = {}
  225.  
  226.     for i in range(1, count_file_in_folder(path_to_csv_file, "csv")):
  227.         list_result = []
  228.         for j in range(1, len_test + 1):
  229.             if i == 1:
  230.                 dict_result_tmp['{}{}'.format(type_test, j)] = 0
  231.             question = '{}{}.firstQuestionDisplayTime'.format(type_test, j)
  232.             response = '{}{}.firstResponseTime'.format(type_test, j)
  233.             if write_result == 'on':
  234.                 print('{}.csv'.format(i), ' - ', '{}{}'.format(type_test, j), ' arithmetic_sum = ',
  235.                       arithmetic_sum(r'{}/{}.csv'.format(path_to_csv_file, i, type_test, j), question, response))
  236.  
  237.                 list_result.append(arithmetic_sum(r'{}/{}.csv'.format(path_to_csv_file, i, type_test, j)
  238.                                                   , question, response))
  239.                 dict_result_tmp['{}{}'.format(type_test, j)] += list_result[j - 1]
  240.             elif write_result == 'off':
  241.                 list_result.append(arithmetic_sum(r'{}/{}.csv'.format(path_to_csv_file, i, type_test, j)
  242.                                                   , question, response))
  243.                 dict_result_tmp['{}{}'.format(type_test, j)] += list_result[j - 1]
  244.  
  245.     #     print(dict_result_tmp)
  246.     list_result = []
  247.     x = []
  248.     y = []
  249.     for key in dict_result_tmp:
  250.         list_result.append(dict_result_tmp[key] / len_test)
  251.  
  252.     #     print(list_result)
  253.  
  254.     for i in range(len_test):
  255.         x.append(str(type_test) + str(i))
  256.  
  257.     #     print(x)
  258.     y = list_result
  259.  
  260.     plt.xlabel('Номер вопроса')
  261.     plt.ylabel('Время ответа на вопрос, мсек')
  262.     plt.plot(x, y)
  263.  
  264.  
  265. def main():
  266.     """
  267.    Главная функция - точка входа. Она же управляет остальными.
  268.  
  269.    :return:
  270.        Ничего не возвращает.
  271.    """
  272.  
  273.     graph('CSV_FILE', 'A', 12, write_result='on')
  274.  
  275.  
  276. if __name__ == "__main__":
  277.     main()
  278.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement