如何修复这个索引错误?

发布于 2025-01-16 22:09:38 字数 1220 浏览 2 评论 0原文

该代码接收一个 import_file ,其中包含元素周期表的元素,写入时不带空格,例如

CrCoRaLiBhMnMdSmNhPbCaUUMo...

然后程序将俄语元素周期表的元素从 json 文件读取到字典中,并将它们写入俄语的 output_file 中,也不带空格,因此该行

CrCoRa...

转变为

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

等等。

问题是臭名昭著的 IndexError,它发生在 p_t: 行的 if (i[n] + i[n+1]) 中。我尝试将 while n <= len(i): 更改为 while n <= len(i) - 1:,但没有帮助。

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')

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')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牛↙奶布丁 2025-01-23 22:09:38

是的,你检查 i[n+1] 但你不知道它是否存在,所以你有一个 IndexError,在 python 中切片字符串也会切片,即使没有你想要切片的字符数量,所以没有索引错误。
你可以尝试这个代码:

    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

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
倾城泪 2025-01-23 22:09:38

忽略语言翻译问题,我建议有一个离散函数,它返回元素符号列表,然后从那里开始。

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

这允许将符号拆分为多行,但本身拆分为 2 行的 2 字符符号将不起作用

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文