2014-03-19 21 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)