gpt4 book ai didi

python - 我在将文本文件解析为字典时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:13:42 24 4
gpt4 key购买 nike

我有一个文本文件,我想将它加载到 Python 字典中。

文本看起来像这样,制表符分隔:

Form Dosage ReferenceDrug drugname activeingred INJECTABLE; INJECTION 20,000 UNITS/ML LIQUAEMIN SODIUM HEPARIN SODIUM INJECTABLE; INJECTION 40,000 UNITS/ML LIQUAEMIN SODIUM HEPARIN SODIUM INJECTABLE; INJECTION 5,000 UNITS/ML LIQUAEMIN SODIUM HEPARIN SODIUM

现在我的代码看起来像这样,但它不起作用(列表索引超出范围,并且没有任何内容被推送到字典)。我不知道我哪里错了,不是程序员。谢谢你的帮助。

import sys

def load_medications(filename):
meds_dict = {}
f = open(filename)
l = " "
# print f.read()
for line in f:
fields = l.split("\t")
ApplNo = fields[0]
ProductNo = fields[1]
Form = fields[2]
Dosage = fields[3]
ProductMktStatus = fields[4]
TECode = fields[5]
ReferenceDrug = fields[6]
DrugName = fields[7]
ActiveIngred = fields[8]

meds = {
"ApplNo": ApplNo,
"ProductNo": ProductNo,
"Form": Form,
"Dosage": Dosage,
"ProductMktStatus": ProductMktStatus,
"TECode": TECode,
"ReferenceDrug": ReferenceDrug,
"DrugName": DrugName,
"ActiveIngred": ActiveIngred
}
meds_dict[DrugName] = meds
f.close()
return meds_dict


def main():
x = load_medications("druglist.txt")
print x



if __name__ == "__main__":
main()

最佳答案

试试 line.split 而不是 l.split

关于python - 我在将文本文件解析为字典时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11893097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com