[英]How to iterate over x amount of lines in a .txt file
我正在嘗試編寫一個程序來對文件中的行進行排序和標記。 例如,假設我有一家健康診所的.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>
任何幫助將不勝感激。
這似乎很可行。 我認為這樣的事情應該起作用...
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
用完時,它不再占用任何行,但是file對象會記住它在下一次讀取時的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.