0

次のようなテキストを含む file.txt を取得しようとしています:

<a> hello 
<a>world 

how <a>are 
</a>you?</a><a></a></a>

次のようなテキストに変換します。

<a> 
    hello 
    <a> 
        world how 
        <a> 
            are 
        </a> 
        you? 
    </a> 
<a> 
</a> 

私の最初の考えは、タグと content(list) を保持する XML アイテムを作成し、そのリスト内にコンテンツを保持する XML アイテムをさらにネストすることでしたが、しばらくすると、間違った方法で行っているように感じます。

このため、Element tree のようなライブラリを使用することはできません。問題をゼロから解決したいと考えています。私はすべての答えを探しているわけではありません。役に立たないコードベースを考え出すのに時間を無駄にしないように、誰かが正しい方向を選択するのを手伝ってくれることを望んでいます.

-----------------------------------以下回答-------------- -------------

from stack import Stack
import re
import sys

def findTag(string):
    # checks to see if a string has an xml tag returns the tag or none
    try:
        match = re.search(r"\<(.+?)\>", string)
        return match.group(0), match.start(0)
    except:
        return None

def isTag(string):
    # checks to see if a string is a tag and returns true or false.
    try:
        match = re.search(r"\<(.+?)\>", string)
        match.group(0)
        return True
    except:
        return False
    else:
        return False


def split_tags_and_string(string):
    #splits up tag and string into a list
    L = []
    for line in s.split("\n"):
        temp = line
        while len(temp) >0: #string still has some characters
            #print("line: " + temp)
            tag_tuple = (findTag(temp)) #returns a tuple with tag and starting index
            #print("tag_tuple: "+ str(tag_tuple))
            if tag_tuple is not None: #there is a tag in the temp string
                if tag_tuple[1] == 0: #tag is the front of temp string
                    L.append(tag_tuple[0].strip())
                    temp = temp.replace(tag_tuple[0], '', 1)
                    temp = temp.strip()
                else: #tag is somewhere else other than the front of the temp string
                    L.append(temp[0:tag_tuple[1]].strip())
                    temp = temp.replace(temp[0:tag_tuple[1]], '', 1)
                    temp = temp.strip()
            else: #there is no tag in the temp string
                L.append(temp.strip())
                temp = temp.replace(temp, '')
    return L


def check_tags(formatted_list):
    # verifies that the xml is valid
    stack = Stack()
    x=0
    try:
        #print(formatted_list)
        for item in formatted_list:
            tag = findTag(item)

            #print("tag: "+ str(tag))
            if tag is not None:
                if tag[0].find('/') == -1:
                    endtag = tag[0][0:1] + '/' +tag[0][1:]
                    #print(endtag)
                    if formatted_list.count(tag[0]) != formatted_list.count(endtag):
                        #print("tag count doesn't match")
                        return False, x
                if tag[0].find('/') == -1:
                    #print("pushing: "+tag[0])
                    stack.push(tag[0])
                else:
                    #print("popping: "+tag[0])
                    stack.pop()
            x+=1
    except:
        return False,x
    if stack.isEmpty():
        return True,x
    else:
        return False,x

def print_xml_list(formatted_list):

    indent = 0
    string = str()
    previousIsString = False
    #print(formatted_list)
    for item in formatted_list:
      #print("previous = " + str(previousIsString))
      #print(item)
        if len(item) > 0:
            if isTag(item) == True and item.find('/') == -1:#the item is a tag and not and end tag
                if previousIsString == True and string[len(string)-5:].find('\n') == -1:
                    #add a newline if there isn't one already
                    string+='\n'
                string+=('    '*indent+item+'\n')
                indent+=1 #increases indent
                previousIsString = False #previous isn't a string
            if isTag(item) == True and item.find('/') != -1: #the item is a tag and also an end tag
                if previousIsString == True:
                    string+='\n'
                indent-=1 # reduces indent
                string+=('    '*indent+item+'\n')
                previousIsString = False #previous isn't a string
            if isTag(item) == False:
                if previousIsString:
                    string+=(' '+item+' ') #adds item and no tab space
                else:
                    string+=('    '*indent+item+' ') #adds item with tabs before
                previousIsString = True # previous is a string


    return string


if __name__ == "__main__":

    filename = input("enter file name:  ")
    file = open(filename, 'r')
    s = file.read()


    formatted = split_tags_and_string(s) #formats the string and tags into a list called formatted
    isGood = check_tags(formatted) # makes sure the xml is valid
    if isGood[0] == False: #if the xml is bad it says so and ends the program
        print("The xml file is bad.")
    else:
        string = print_xml_list(formatted) #adds indentation and formatting to the list and turns it into a string
        print(string) #prints the final result

誰も答えを提供しなかったので、これがxmlを解析する私の基本的な方法です。次のようなものを処理する機能がありません

4

1 に答える 1

0

上記の回答を提供しました。うまくいけば、これは同じような好奇心を持つ誰かに役立つでしょう.

于 2013-10-15T05:12:10.627 に答える