Output an OrderedDict to CSV

2024/11/19 12:31:20

I read a CSV file and use the usaddress library to parse an address field. How do I write the resulting OrderedDicts to another CSV file?

import usaddress
import csvwith open('output.csv') as csvfile:reader = csv.DictReader(csvfile)for row in reader:addr=row['Case Parties Address']data = usaddress.tag(addr)print(data)
(OrderedDict([('AddressNumber', u'4167'), ('StreetNamePreType', u'Highway'), ('StreetName', u'319'), ('StreetNamePostDirectional', u'E'), ('PlaceName', u'Conway'), ('StateName', u'SC'), ('ZipCode', u'29526-5446')]), 'Street Address')
Answer

see this github issue for a solution:

import csvkit
import usaddress# expected format in input.csv: first column 'id', second column 'address'
with open('input.csv', 'rU') as f:reader = csvkit.DictReader(f)all_rows = []for row in reader:try:parsed_addr = usaddress.tag(row['address'])row_dict = parsed_addr[0]except:row_dict = {'error':'True'}row_dict['id'] = row['id']all_rows.append(row_dict)field_list = ['id','AddressNumber', 'AddressNumberPrefix', 'AddressNumberSuffix', 'BuildingName', 'CornerOf','IntersectionSeparator','LandmarkName','NotAddress','OccupancyType','OccupancyIdentifier','PlaceName','Recipient','StateName','StreetName','StreetNamePreDirectional','StreetNamePreModifier','StreetNamePreType','StreetNamePostDirectional','StreetNamePostModifier','StreetNamePostType','SubaddressIdentifier','SubaddressType','USPSBoxGroupID','USPSBoxGroupType','USPSBoxID','USPSBoxType','ZipCode', 'error']with open('output.csv', 'wb') as outfile:writer = csvkit.DictWriter(outfile, field_list)writer.writeheader()writer.writerows(all_rows)

some notes:

  • because each tagged address can have a different set of keys, you should define the columns in the output with all possible keys. this isn't a problem, because we know all the possible usaddress labels
  • the usaddress tag method will raise an error if it is unable to concatenate address tokens in an intuitive way. these errors should be captured in the output
https://en.xdnf.cn/q/119954.html

Related Q&A

min() arg is an empty sequence

I created a function that consumes a list of values and produces the average. However it only works when I use integer values. I get the following error when I make the values into floats:min() arg is …

Removing last words in each row in pandas dataframe

A dataframe contains a column named full_name and the rows look like this: full_name Peter Eli Smith Vanessa Mary Ellen Raul Gonzales Kristine S Lee How do I remove the last words and add an additi…

Object of type function has no len() in python

I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.Here is the code that Ive wrote.def main():while True:userInput(…

My If condition within a while loop doesnt break the loop

Struggling to get my code for the final room to finish the text-based game assigned to me. I essentially want the player to be forced to get all 6 items prior to entry. Any help is greatly appreciated.…

Adding strings, first, first + second, etc

Program has to be able adding strings from the list and output them in sequence but in the way: 1 string 1 + 2 string 1 + 2 + 3 string ...def spacey(array):passe = ""i = ""m = []for…

Store Variables in Lists python

So I have tried to do this, and I think its clear what I want, I want to store the message variables that I have made in a List and then use this for printing, I wonder why does this not work?items = …

How can I kill the explorer.exe process?

Im writing a script which is meant to kill explorer.exe. I searched a bit about it and the best answer Ive seen uses the taskkill command. I tried it, but when I run it on my computer it says it worked…

A presence/activity set command?

So, I was wondering if there could be a command I could write that allows me to set the bots presence and activity (ex. ~~set presence idle or ~~set activity watching "people typing ~~help") …

Inverted Index in Python not returning desired results

Im having trouble returning proper results for an inverted index in python. Im trying to load a list of strings in the variable strlist and then with my Inverse index looping over the strings to return…

Remove white space from an image using python

There are multiple images that have white spaces that I need to remove. Simply crop the image so as to get rid of the white spaces Heres the code I tried so far (this is a result of search) import nump…