2013-12-10 87 views
0

我試圖使用XML標記對文本文件中的數據進行排序。我知道所有的圖書館,但這不是我想要這樣做的方式。如果我有一個文件是:如何將文本文件中的下一行寫入新的文本文件

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

我需要的輸出看起來像:

<patient>  
<patientID>A31415</patientID> 
<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>  
<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> 

我的代碼是:

def codeData(filename): 
    newFile = filename 
    newFile = newFile.replace(".txt", "") 
    newFile = str(newFile) + "XML.txt"  
    originalFile = open(filename,'r')  
    firstLine = originalFile.readline() 
    secondLine = originalFile.readline() 
    original = originalFile.readlines() 
    index = 0 
    file = open(newFile, 'w') 
    for line in original: 
     index = index + 1 
     if index%11 == 1: 
      file.write('<patientID>'+str(original[0]).strip('\n')+'</patientID>\n') 
     if index%11 == 2: 
      file.write('<age>'+str(original[1]).strip('\n')+'</age>\n') 
     if index%11 == 3: 
      file.write('<gender>'+str(original[2]).strip('\n')+'</gender>\n') 
     if index%11 == 4: 
      file.write('<height>'+str(original[3]).strip('\n')+'</height>\n') 
     if index%11 == 5: 
      file.write('<weight>'+str(original[4]).strip('\n')+'</weight>\n') 
     if index%11 == 6: 
      file.write('<HBA1C>'+str(original[5]).strip('\n')+'</HBA1C>\n') 
     if index%11 == 7: 
      file.write('<cholesterol>'+str(original[6]).strip('\n')+'</cholesterol>\n') 
     if index%11 == 8: 
      file.write('<smoker>'+str(original[7]).strip('\n')+'</smoker>\n') 
     if index%11 == 9: 
      file.write('<systolic>'+str(original[8]).strip('\n')+'</systolic>\n') 
     if index%11 == 10: 
      file.write('<diastolic>'+str(original[9]).strip('\n')+'</diastolic>\n') 

但有了這個代碼,我輸出重複只有一個患者。我知道這是因爲我正在指定寫一個特定的行。我的輸出是:

<patientID>A31415</patientID> 
<age>54</age> 
<gender>M</gender> 
<height>180</height> 
<weight>98</weight> 
<HBA1C>6.7</HBA1C> 
<cholesterol>100</cholesterol> 
<smoker>No</smoker> 
<systolic>130</systolic> 
<diastolic>65</diastolic> 
<patientID>A31415</patientID> 
<age>54</age> 
<gender>M</gender> 
<height>180</height> 
<weight>98</weight> 
<HBA1C>6.7</HBA1C> 
<cholesterol>100</cholesterol> 
<smoker>No</smoker> 
<systolic>130</systolic> 

所以我的問題是如何在文件中寫下一行,而不是重複。 任何幫助,將不勝感激。是的,所有的信息都是完全組成的。

回答

2
  1. 使用for index, line in enumerate(original)遍歷您的輸入,而無需跟蹤指數自己。

  2. 訪問當前line for-loop不是使用(尤其是硬編碼)索引,如original[0]

  3. 一旦一切按照您的要求工作,您可能需要考慮使用XML標記的列表或字典,而不是您現在使用的長列表if

+0

謝謝,但現在又有一個問題,當舒張期應該是最後一個時,怎麼會收縮期結束呢? – jboyda5

+0

您的數據集每行10行,因此您必須使用'%10'而不是'%11'(假設您使用的是從零開始的索引)並將結果與​​值0至9進行比較(而不是1至10)。 –

相關問題