【问题标题】:How to iterate over x amount of lines in a .txt file如何遍历 .txt 文件中的 x 行
【发布时间】:2013-12-25 02:35:42
【问题描述】:

我正在尝试编写一个程序来对文件中的行进行排序和标记。例如,假设我有一个健康诊所的 .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>

任何帮助将不胜感激。

【问题讨论】:

  • 请向我们展示您已经尝试过的代码。

标签: python python-3.x


【解决方案1】:

这似乎很可行。我认为这样的事情应该可以工作......

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 会在两个输入迭代中较短的那个处截断。换句话说,它从file_keys 中获取1 个元素并将其与文件中的1 行匹配。当file_keys 用完时,它不再占用任何行,但文件对象会记住它的位置以供下次读取。

【讨论】:

  • 这行得通,也是我处理这个问题的方式。不过,您可能想解释一下为什么会这样。
  • 虽然只适用于一名患者....也许for patient in iter(lambda: dict(zip(file_keys, fin)), {}) 代替
  • @MartijnPieters,你确定吗? zip 记录为在较小的序列用完后截断。
  • @MarkRansom:完全正确。所以它只会从fin 中读取len(file_keys) 行。这就是 为什么 有效。当然,前提是你添加了一个循环。
  • @MartijnPieters OP 似乎遇到的问题是他们希望能够从文件中提取该格式的 多个 患者......因此,我们错过了这个循环
猜你喜欢
  • 2019-05-05
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多