关于重新分解python代码

时间:2014-03-19 02:46:26

标签: python python-2.7

所以我有这个python文件,它可以查找所有"标签"标记在XML文件中并对其进行一些修改。 label是一个包含最多三行的字符串。代码正在操纵XML文件。

                    #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"
标签#2中的注意事项第二行和第三行中的单词不是大写字母,这不是我想要的。我想帮助纠正我的程序逻辑,这样我就不应该写两次标签了。

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 个答案:

答案 0 :(得分: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)