gpt4 book ai didi

python - 如何从文本文件创建嵌套字典

转载 作者:行者123 更新时间:2023-12-05 09:28:19 24 4
gpt4 key购买 nike

所以,我的文件看起来像这样:

Intestinal infectious diseases (001-003) 
001 Cholera
002 Typhoid and paratyphoid fevers
003 Other salmonella infections

Tuberculosis (004-006)
004 Primary tuberculous infection
005 Pulmonary tuberculosis
006 Other respiratory tuberculosis

.
.
.

我应该制作一个嵌套字典,其中疾病组作为键,包含疾病代码和名称的字典作为第一个字典的值。我在将疾病代码分成它们自己的疾病组时遇到了一些麻烦。这是我到目前为止所做的:

import json

icd9_encyclopedia={}
lines = []
f = open("icd9_info.txt", 'r')
for line in f:
line = line.rstrip("\n")
if line[0].isnumeric() == True:
icd9_encyclopedia[line] = ???




f.close()

最佳答案

解决方案

import itertools
from pathlib import Path

# load text lines
lines = Path('data.txt').read_text().split('\n')

# build output dictionary
icd9_encyclopedia = {
# build single group dictionary
group_name: {
int(code): disease_name
# split each disease line into code and text name
for disease_string in disease_strings
for (code, _, disease_name) in [disease_string.partition(' ')]
}
# get groups separated by an empty line
# isolate first item in each group as its name
for x, (group_name, *disease_strings) in itertools.groupby(lines, bool) if x
}

结果

{'Intestinal infectious diseases (001-003)': {1: 'Cholera',
2: 'Typhoid and paratyphoid '
'fevers',
3: 'Other salmonella infections'},
'Tuberculosis (004-006)': {4: 'Primary tuberculous infection',
5: 'Pulmonary tuberculosis',
6: 'Other respiratory tuberculosis'}}

关于python - 如何从文本文件创建嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71433034/

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