Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. def corrector (string, sep=","):
  2.     '''
  3.     Функция разбиения на строки файлов csv.
  4.    
  5.     string -- строка файла csv.
  6.     sep -- разделитель.
  7.     '''
  8.    
  9.     escaped = False # Метка экранирования
  10.     out = []
  11.     buff = [] # Буфер в который будут записываться строки
  12.     for i in string.split(","):
  13.         if '"' in i : # От этого условия можно в принципе и отказаться
  14.             i_index = 0
  15.             while i_index != -1:
  16.                 i_index = i.find('"', i_index)
  17.                 # Наверное правильнее было бы использовать index,
  18.                 # но мне лень.
  19.                 if i_index != -1:
  20.                     if i_index == len(i)-1:
  21.                         # Очевидно, что если кавычки последние в строке,
  22.                         # то они единичные
  23.                         escaped = not (escaped)
  24.                         i_index = -2 # Да, знаю, грязный хак. Но лень...
  25.                     else:
  26.                         if i[i_index+1] == '"':
  27.                             i = i[:i_index] + i[i_index+1:]
  28.                         else:
  29.                             escaped = not (escaped)
  30.                     i_index = i_index+1
  31.             else:
  32.                 buff.append(i)
  33.         else:
  34.             buff.append(i)
  35.         if not(escaped):
  36.             # Сброс буфера
  37.             out.append(",".join(buff))
  38.             buff = []
  39.     return out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement