如何修复这个索引错误?
该代码接收一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,你检查 i[n+1] 但你不知道它是否存在,所以你有一个 IndexError,在 python 中切片字符串也会切片,即使没有你想要切片的字符数量,所以没有索引错误。
你可以尝试这个代码:
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:
忽略语言翻译问题,我建议有一个离散函数,它返回元素符号列表,然后从那里开始。
这允许将符号拆分为多行,但本身拆分为 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.
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