在python的csv文件中指定单个单元格

时间:2019-03-12 05:00:43

标签: python excel csv

我在这段代码中苦苦挣扎,似乎无法正确执行。我正在尝试从python中的csv访问和打印单个单元格值。我有行和列的列表来指定每个单个单元格,但是当我尝试将文件转换为列表然后指定[row] [column]时遇到索引错误。无论如何,我可以不用熊猫来获得单个单元格的str值?如果可能的话,我宁愿使用csv模块

import csv
from csv import reader
import json

categories = { '1':'Unacceptable', '2':'Edit'}

def get_annotation_input():
    while True:
        try:
            annotation = int(input("Annotation: "))
            if annotation not in range (1,3):
                raise ValueError
            return annotation
        except ValueError:
            print("Enter 1 or 2") 


def annotate():
    annotator = input("What is your name? ")
    print(''.join(["-"]*50))

    with open('annotations_full.csv', 'rU') as infile:
              response_reader = csv.DictReader(infile)
              responses = {}
              for row in response_reader:
                  for header, response in row.items():
                      try:
                          responses[header].append(response)
                      except KeyError:
                          responses[header] = [response]


              for i in range(len(ROWS)):
                  ROWS[i] = int(ROWS[i])
              COLUMNS = responses['question_number']
              csv_file = csv.reader(open('results.csv'))
              header = next(csv_file)
              text_question = next(csv_file)
              for i in range(len(COLUMNS)):
                  COLUMNS[i] = (header.index(COLUMNS[i]))
              #print(ROWS,COLUMNS)

              for i,j in zip(ROWS,COLUMNS):
                  current_row = i
                  current_column = j
                  print("Current row number: ", current_row)
                  print("Annotate the following answer as 1-Unacceptable, 2-Edit")
                  print(header[current_column])
                  print(text_question[current_column], '\n')
                  #WANT TO PRINT SINGLE SPECIFIED CELL TEXT[CURRENT_ROW][CURRENT COLUMN] FROM CSV HERE 
                  annotation = get_annotation_input()
                  if annotation == 2:
                      edited_response = input("Edit the response: " )
                  else:
                      edited_response = "CAN NOT BE EDITED"

                      with open("annotations.json", mode='a') as annotation_file:
                          annotation_data = {'annotator' : annotator, 'row_number': current_row, 'question_number': header[current_column], 'annotation' : categories[str(annotation)], 'edited' : edited_response}
                          json.dump(annotation_data, annotation_file)
                          annotation_file.write('\n')



if __name__ == "__main__":
    annotate()

CSV file 'annotations_full.csv CSV file 'results.csv'

0 个答案:

没有答案
相关问题