Domanda

I'm using the python packages xlrd and xlwt to read and write from excel spreadsheets using python. I can't figure out how to write the code to solve my problem though.

i have a column in my first spreadsheet that has state names in the form of 2 letter abbreviations and the full name (some all lowercase, some with the first letter capitalised). I'm trying to write another sheet that reads the names on the first sheet, sees if they match the names on the second sheet, and writes them onto the third sheet as the state abbreviations found on the second sheet. Does this make sense?

anyway, without making fifty separate "for" loops, I'm not sure how to do it. Here's what I have thus far, but running it wrote a blank first column.

import xlrd #reads
import xlwt #writes

input_book = xlrd.open_workbook("file_path_here")
input_sheet = input_book.sheet_by_index(0)
state_book = xlrd.open_workbook("file_path2_here")
state_sheet = state_book.sheet_by_index(0)
output_book = xlwt.Workbook()
output_sheet = output_book.add_sheet('test')

for row in range(input_sheet.nrows):
    state = input_sheet.cell_value(row, colx=1) #state names are in col 1
    Value1 =input_sheet.cell_value(row, colx=2) #data being left unchanged, just copied to output sheet
    Value2 =input_sheet.cell_value(row, colx=3)
    Value3 =input_sheet.cell_value(row, colx=4)
    for name in range(state_sheet.nrows):  #a sheet with state names in col 0, state abrevs in col 1
        state_name = state_sheet.cell_value(name,colx=0)
        state_abrev = state_sheet.cell_value(name, colx=1)
        if state.lower() == state_name:
            output_sheet.write(row,0,state_abrev)
    output_sheet.write(row,1,Value1)
    output_sheet.write(row,2,Value2)
    output_sheet.write(row,3,Value3)

print ('done')
output_book.save('output.xls')
È stato utile?

Soluzione

This sounds like a dictionary - first create a dictionary

state_abbrs = {}
for name in range(state_sheet.nrows):  #a sheet with state names in col 0, state abrevs in col 1
    state_name = state_sheet.cell_value(name, colx=0)
    state_abrev = state_sheet.cell_value(name, colx=1)
    state_abbrs[state_name.lower()] = state_abbr

Then use it:

for row in range(input_sheet.nrows):
    state = input_sheet.cell_value(row, colx=1) #state names are in col 1
    Value1 = input_sheet.cell_value(row, colx=2) #data being left unchanged, just copied to output sheet
    Value2 = input_sheet.cell_value(row, colx=3)
    Value3 = input_sheet.cell_value(row, colx=4)

    output_sheet.write(row, 0, state_abbrs.get(state.lower(), '')
    output_sheet.write(row, 1, Value1)
    output_sheet.write(row, 2, Value2)
    output_sheet.write(row, 3, Value3)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top