Как мне обрабатывать данные из файла csv, в котором в одном из полей есть запятая?

#python #csv

#python #csv

Вопрос:

запятые в данных в файле csv

это набор данных, с которым я работаю, загруженный с официального сайта ВОЗ

это мой функциональный код, но часть записи содержит запятую, она содержится в кавычках в начале и конце поля, но я не знаю, как сохранить ее как одну строку, прежде чем она попадет в параллельные массивы, я не могу просто импортировать csv, потому что его для моего sqa выше (15-16 лет для тех, кто не из Шотландии) курс вычислений, и я должен сделать это вручную

в одном из названий стран есть запятая

2020-09-30, BQ, «Бонэйр, Синт-Эстатиус и Саба», AMRO,9,115,0,1

(«Бонэйр, Синт-Эстатиус и Саба»)

где, как и в остальных, нет и нет кавычек

2020-09-08,AF, Афганистан, EMRO,96,38494,3,1415

(Афганистан)

и в основном он разбивается там, где я этого не хочу, и у меня осталось 9 полей, когда их должно быть только 8

 def get_data():

    country_code, country_code, country, who_region, new_cases, cumulative_cases, new_deaths, cumulative_deaths = [], [], [], [], [] , [], [], []
    with open("datacsv\todays_data.csv") as f:
        next(f)
        t=0
        for line in f:
            field = line.split(",")
            country_code.append(field[0])
            country_code.append(field[1])
            country.append(field[2])
            who_region.append(field[3])
            cumulative_cases.append(int(field[5]))
            new_deaths.append(int(field[6]))
            cumulative_deaths.append(int(field[7].strip("n")))
    print("data successfully read")
    return country_code, country_code, country, who_region, new_cases, cumulative_cases, new_deaths, cumulative_deaths
  

Комментарии:

1. Для такого рода проблем стек является полезной структурой данных. Подумайте о том, чтобы поместить первую кавычку в стек, а затем вставить вторую.

2. Вам нужно будет выполнить собственный синтаксический анализ строки, который вы не можете использовать split() для этого.

Ответ №1:

Код здесь только для вашего примера, максимум только одна специальная строка кавычек.

 from itertools import repeat

lines = [
    '2020-09-30,BQ,"Bonaire, Sint Eustatius and Saba",AMRO,9,115,0,1',
    '2020-09-08,AF,Afghanistan,EMRO,96,38494,3,1415',
]

magic = 'a0b1c2d3e4'  # magic string won't be found in your csv file
result = []
for line in lines:
    if '"' in line:
        temp = line.split('"')
        temp[1] = temp[1].replace(',', magic)
        line = '"'.join(temp)
    result.append(list(map(str.replace, line.split(','), repeat(magic), repeat(','))))
  
 >>> result
[['2020-09-30', 'BQ', '"Bonaire, Sint Eustatius and Saba"', 'AMRO', '9', '115', '0', '1'],
 ['2020-09-08', 'AF', 'Afghanistan', 'EMRO', '96', '38494', '3', '1415']]
  

Ответ №2:

Учитывая, что это задание для курса вычислительной техники, скорее всего, вы собираетесь создать простой анализатор. Псевдокод будет выглядеть примерно так:

 data = []
for char in file:
  record = []
  is_in_quotes = false
  cell = ''

  switch char:
    case ',':
      if is_in_quotes:
        # If we are inside a quoted string, treat the comma as part of the cell's value
        cell.append(char)
      else:
        # Otherwise, it denotes the end of a cell
        record.append(cell)
        cell = ''
    case '"':
      # We assume that
      # - there are only ever two double quotes within a cell
      # - the double quotes only appear right after the leading command and right before the trailing comma
      # Because of that, we can simply toggle the state
      is_in_quotes = !is_in_quotes
    case 'n':
      # At line end, we first add the last cell's value to the record
      record.append(cell)
      cell = ''
      # Then we add the record to the data set
      data.append(record)
      record = []
    default:
      # Any other character is simply treated as part of the cell's value
      cell.append(char)