如何在.txt文件中迭代x行

2024-07-01 08:01:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个程序来排序和标记文件中的行。例如,假设我有一个健康诊所的.txt文件,其中包含关于患者的各种信息。我想标记信息。假设数据按以下顺序给出:

Patient ID  
Age 
Gender  
Height  
Weight  
HBA1C level 
Cholesterol 
Smoker status   
Systolic BP 
Diastolic BP

假设该文件包含以下信息(所有这些信息都是组成的):

A31415  
54  
M   
180 
90  
6.7 
100 
No  
130 
65  
A32545  
62  
F   
160 
80  
7.2 
120 
Yes 
180 
92

我的问题是为每个病人写一个循环

A31415  
54  
M   
180 
90  
6.7 
100 
No  
130 
65

作为一个病人

A32545  
62  
F   
160 
80  
7.2 
120 
Yes 
180 
92

作为第二个。我正在努力让代码产生以下结果:

<patient>       
<patientID> A31415  </patientID>    
<clinic>    UIHC    </clinic>   
<age>   54  </age>  
<gender>    M   </gender>   
<height>    180 </height>   
<weight>    90  </weight>   
<hba1c> 6.7 </hba1c>    
<cholesterol>   100 </cholesterol>  
<smoker>    No  <smoker>    
<systolic>  130 </systolic> 
<diastolic> 65  </diastolic>    
</patient>  
<patient>       
<patientID> A32545  </patientID>    
<clinic>    UIHC    </clinic>   
<age>   62  </age>  
<gender>    F   </gender>   
<height>    160 </height>   
<weight>    80  </weight>   
<hba1c> 7.2 </hba1c>    
<cholesterol>   120 </cholesterol>  
<smoker>    Yes </smoker>   
<systolic>  180 </systolic> 
<diastolic> 92  </diastolic>    
</patient>

任何帮助都将不胜感激。你知道吗


Tags: 文件信息agegenderheightweightclinicpatient
1条回答
网友
1楼 · 发布于 2024-07-01 08:01:45

这似乎很可行。我觉得这样应该行得通。。。你知道吗

file_keys = ['Patient ID', 'Age', 'Gender',  
             'Height', 'Weight', 'HBA1C level' 
             'Cholesterol', 'Smoker status',   
             'Systolic BP', 'Diastolic BP']

with open('datafile') as fin:
    user_info = dict(zip(file_keys, fin))
    # Now process user_info into your xml 

当然,这只需要文件中的一个用户。要把它们都弄到手,你需要一个循环。一旦返回的user_info是一个空字典,您就知道您拥有了所有的用户。你知道吗

with open('datafile') as fin:
    while True:
        user_info = dict(zip(file_keys, fin))
        if not user_info:  # empty dict.  we're done.
            break
        # Now process user_info into your xml

之所以这样做是因为zip将在两个输入iterable中的较短位置截断。换句话说,它从file_keys中获取1个元素,并将其与文件中的1行匹配。当file_keys用完时,它不再占用任何行,但是file对象会记住它的位置,以便下次读取。你知道吗

相关问题 更多 >

    热门问题