Может ли кто-нибудь помочь мне. Я сталкиваюсь с проблемой при написании этого кода с Python - PullRequest
0 голосов
/ 04 мая 2020

Мы работаем со списком цветов и информацией о каждом из них. Функция create_file записывает эту информацию в файл CSV. Функция contents_of_file считывает этот файл в записи и возвращает информацию в хорошо отформатированном блоке. Заполните пробелы в функции contents_of_file, чтобы превратить данные в файле CSV в словарь с помощью DictReader.

import os
import csv

# Create a file with data in it
def create_file(filename):
  with open(filename, "a") as file:
    file.write("name,color,type\n")
    file.write("carnation,pink,annual\n")
    file.write("daffodil,yellow,perennial\n")
    file.write("iris,blue,perennial\n")
    file.write("poinsettia,red,perennial\n")
    file.write("sunflower,yellow,annual\n")

# Read the file contents and format the information about each row
def contents_of_file(filename):
  return_string = ""

  # Call the function to create the file 
  create_file(filename)

  # Open the file
  with open(filename) as file:
    # Read the rows of the file into a dictionary
    f = csv.reader(file)
    # Process each item of the dictionary
    for row in f:
      name, color, type = row
      return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"])
  return return_string

#Call the function
print(contents_of_file("flowers.csv"))

[See the error][1]


  [1]: https://i.stack.imgur.com/UycSc.jpg

1 Ответ

0 голосов
/ 04 мая 2020

Итак, проблема, с которой вы сталкиваетесь, заключается в том, что тип данных row на Line 26 является array, а не dict. Поэтому, если вы используете index элемента вместо ['keyName'], все будет работать нормально.

Замените следующее:

return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"])

с

return_string += "a {} {} is {}\n".format(row[1], row[0], row[2])

В качестве альтернативы, вы можете использовать String Interpolation, чтобы сделать ваш код более читабельным:

return_string += f'a {row[1]} {row[0]} is {row[2]}\n'

Если вы хотите использовать имена столбцов в качестве индексов, вы можете использовать csv.DictReader() вместо csv.reader()

...