如何从python中的字符串中删除引号?

时间:2019-04-27 05:15:31

标签: python-3.x

csv文件以字典格式返回列值。但是我无法使用dic.get(“ name”)从字典中获取值。它显示错误,例如['str'对象没有属性'get']实际的问题是csv返回带格的字典,因此python将其视为string.how如何删除这些行以及如何修复它。请帮忙!


with open('file.csv') as file:
  reader=csv.reader(file)
  count=0
  for idx,row in enumerate(reader):
   dic=row[5]
   if(idx==0):
     continue
   else:
     print(dic.get("name")) 
filename    file_size   file_attributes region_count    region_id   region_shape_attributes region_attributes
adutta_swan.jpg -1  {"caption":"Swan in lake Geneve","public_domain":"no","image_url":"http://www.robots.ox.ac.uk/~vgg/software/via/images/swan.jpg"}   1   0   {"name":"rect","x":82,"y":105,"width":356,"height":207} {"name":"not_defined","type":"unknown","image_quality":{"good":true,"frontal":true,"good_illumination":true}}
wikimedia_death_of_socrates.jpg -1  {"caption":"The Death of Socrates by David","public_domain":"yes","image_url":"https://en.wikipedia.org/wiki/The_Death_of_Socrates#/media/File:David_-_The_Death_of_Socrates.jpg"}  3   0   {"name":"rect","x":174,"y":139,"width":108,"height":227}    {"name":"Plato","type":"human","image_quality":{"good_illumination":true}}
wikimedia_death_of_socrates.jpg -1  {"caption":"The Death of Socrates by David","public_domain":"yes","image_url":"https://en.wikipedia.org/wiki/The_Death_of_Socrates#/media/File:David_-_The_Death_of_Socrates.jpg"}  3   1   {"name":"rect","x":347,"y":114,"width":91,"height":209} {"name":"Socrates","type":"human","image_quality":{"frontal":true,"good_illumination":true}}
wikimedia_death_of_socrates.jpg -1  {"caption":"The Death of Socrates by David","public_domain":"yes","image_url":"https://en.wikipedia.org/wiki/The_Death_of_Socrates#/media/File:David_-_The_Death_of_Socrates.jpg"}  3   2   {"name":"ellipse","cx":316,"cy":180,"rx":17,"ry":12}    {"name":"Hemlock","type":"cup"}

2 个答案:

答案 0 :(得分:0)

使用DictReader可以将csv读取为字典!

import csv
import json

with open('graph.csv') as file:
    #Read csv as dictreader
    reader=csv.DictReader(file)
    count=0
    #Iterate through rows
    for idx,row in enumerate(reader):
        #Load the string as a dictionary 
        region_shape_attributes = json.loads(row['region_shape_attributes'])
        print(region_shape_attributes['name'])

答案 1 :(得分:0)

`import csv
import ast
with open('file.csv') as file:
    #Read csv as dictreader
    reader=csv.DictReader(file)
    count=0
    #Iterate through rows
    for idx,row in enumerate(reader):
       #print(row)
       row_5=row['region_shape_attributes']
       y=ast.literal_eval(row_5)
       print(y.get("name"))`


this code also work to me