2014-03-19 63 views
0

所以我有這個python文件,它查找XML文件中的所有「標籤」標籤並對其進行一些修改。標籤是包含最多三行的字符串。該代碼正在操縱XML文件。在標籤#2的話在二,三線關於重新分解Python代碼

    #1 label="Number of Packets Transmitted by the Source 
          Node of the Path to the Destination Node Of 
          the Path" 
        #2 label="Number of Packets Transmitted by the Source 
          node of the path to the destination node of 
          the path" 

通知是不是這不是我想要的大寫。我希望能幫助我糾正我的程序的邏輯,以便我不應該將標籤寫兩次。

import os 
from io import StringIO, BytesIO 

def splitAndMakeTitleCase(line): 
    # does something not relevant to context 



fileList = open("AllFiles") 
for fileStr in fileList: 
    fileName = fileStr.rstrip('\n') 
    openFile = open(fileName) 
    openNewFile = open(fileName+'TitleCase.xml','w') 
    lines = openFile.readlines() 
    for lineIndex in range(0,len(lines)): 
     line = lines[lineIndex] 
     skip = 0 
     if "label=" in line and "const" not in line: 
      segs = line.split('"') 
      if len(segs) >= 3: 
       pass 
      else: 
       openNewFile.write(lines[lineIndex]) 
       secondTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex + 1]) 
       skip = lineIndex + 1 
       openNewFile.write(secondTitleCaseLine) 
       if '"' not in lines[lineIndex + 1]: 
        thirdTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex + 2]) 
        skip = lineIndex + 1 
        openNewFile.write(thirdTitleCaseLine) 
     openNewFile.write(lines[lineIndex]) 
    openFile.close() 
    openNewFile.close() 
    #cmd = "mv " + fileName + "TitleCase.xml " + fileName 
    #os.system(cmd) 

回答

1

在您的for循環中,您有第一個if,然後在該文件中執行一些打印。之後,您會對該文件執行另一行打印。我認爲你可能需要像這樣的最後一行:

for fileStr in fileList: 
    fileName = fileStr.rstrip('\n') 
    openFile = open(fileName) 
    openNewFile = open(fileName+'TitleCase.xml','w') 
    lines = openFile.readlines() 
    for lineIndex in range(0,len(lines)): 
     line = lines[lineIndex] 
     skip = 0 
     if "label=" in line and "const" not in line: 
      segs = line.split('"') 
      if len(segs) >= 3: 
       pass 
      else: 
       openNewFile.write(lines[lineIndex]) 
       secondTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex + 1]) 
       skip = lineIndex + 1 
       openNewFile.write(secondTitleCaseLine) 
       if '"' not in lines[lineIndex + 1]: 
        thirdTitleCaseLine = splitAndMakeTitleCase(lines[lineIndex + 2]) 
        skip = lineIndex + 1 
        openNewFile.write(thirdTitleCaseLine) 
     else: 
      openNewFile.write(lines[lineIndex]) 
    openFile.close() 
    openNewFile.close() 
    #cmd = "mv " + fileName + "TitleCase.xml " + fileName 
    #os.system(cmd)