Home > Mobile >  How to fix this IndexError?
How to fix this IndexError?

Time:03-25

The code receives an import_file with elements of periodic table, written without space, e. g.

CrCoRaLiBhMnMdSmNhPbCaUUMo...

Then the program reads elements of periodic table in Russian language into a dictionary from json file and write them to output_file in Russian language with no space either, thus the line

CrCoRa...

transforms into

ХромКобальтРадий...

and so on.

The problem is the infamous IndexError, which occurs in the if (i[n] i[n 1]) in p_t: line. I've tried to change while n <= len(i): for while n <= len(i) - 1:, but it doesn't help.

import json

def periodic_table(import_file, output_file):
    p_t = json.load(open('periodic_table.json', encoding = 'utf-8'))
    with open(import_file) as i_f, open(output_file, 'w') as o_f:
        for i in i_f.readlines():
            n = 0
            while n <= len(i):
                if (i[n]   i[n 1]) in p_t: 
                    o_f.write(p_t[i[n]   i[n 1]])
                    n  = 2
                elif (i[n]   i[n 1]   i[n 2]) == 'Uue':
                    o_f.write(p_t['Uue'])
                    n  = 3
                elif i[n] in p_t:
                    o_f.write(p_t[i[n]])
                    n  = 1

periodic_table('import_file_3.txt', 'output_file.txt')

CodePudding user response:

Yes you check i[n 1] but you don't know if it exists, so you have an IndexError, slicing a string in python will slice even if there are not the amount of characters you want to slice, so there is no IndexError. you can try this code:

    def periodic_table(import_file, output_file):
    p_t = json.load(open('periodic_table.json', encoding = 'utf-8'))
    with open(import_file) as i_f, open(output_file, 'w') as o_f:
        for i in i_f.readlines():
            while len(i) > 0:
                if len(i[0:2]) == 2 and i[0:2] in p_t:
                    o_f.write(i[0:2])
                    i = i[2:]
                elif i[0:3] == 'Uue':
                    o_f.write(p_t['Uue'])
                    i = i[3:]
                elif i[0] in p_t:
                    o_f.write(p_t[i[0]])
                    i = i[1:]
                else:
                    break # otherwise it will run forever if you have an error in the file

CodePudding user response:

Ignoring the language translation matter, I would suggest have a discrete function that returns a list of the element symbols then go from there.

def getElementList(filename):
    elist = []
    with open(filename) as elements:
        for e in map(str.strip, elements.readlines()):
            i = 0
            while i < len(e):
                e1, *e2 = e[i:i 2]
                if e2 and e2[0].islower():
                    elist.append(e1 e2[0])
                    i  = 1
                else:
                    elist.append(e1)
                i  = 1
    return elist

This allows for the symbols to be split over multiple lines although a 2-character symbol which itself is split over 2 lines will not work

  • Related