简体   繁体   中英

Find and replace at a particular location in list using python

this is my tag to be inserted in the file

new_tag="newtag"

Below is the file i have in my list ( as input )

  <GrandFather-Tag>

      <unique-Tags>UniqueTag</unique-Tags>

      <unique-Tags>Unique-Tag</unique-Tags>

      <Grandson-Tag>

    <param-name>dsReference</param-name>

    ***THE CORRECT AREA TO INSERT THE NEW TAG.***

      </GrandSon-Tag>

  </GrandFather-tag>

I need to add an entry after Grand-Son tag but anywhere before grandson tag closes.

Since this is a very big xml file, i need to make sure i add entry only after checking if Grand-Father tag is present:

if Grand-Father Tag is present, check for the unique tags till Grandson-Tag, if we get to the line where Grandson-Tag starts. add an entry to the file after grandson-tag but before grandson tag ends and before the grandfather tag ends.

Here's the logic i came up with: but it's failing:

for i in input_file: #List as input

    for j in start_tag_check:   #List which has grandfather tag and grandsontag

        for k in uniquetagchecks:      #List which checks if the tags are present after startcheck but before end_tag_check

            for l in end_tag_check:     #check if the start_tag is ending

               The logic to add entry after start tag and between end tag fails.

all these checks are necessary since the file may have multiple similar tags, so to increase the accuracy i've added all these checks. Can anyone help me here? to correct this logic / a workaround method Thanks in advance

counter=key;
counter -=1
for c,i in enumerate(upper_half):
    if i.startswith('<') and not i.startswith('</'):
        if (i.split('>')[0].split('<')[1]):
            upper_tags.append(i.split('>')[0].split('<')[1])
            upper_tag_index.append(c)

    counter=counter -1;

upper_dict=dict(zip(upper_tag_index,upper_tags))
upper_dict_temp=upper_dict


for index,value in enumerate(upper_half):
    for (k,val) in upper_dict_temp.items():
        if '</'+val+'>' in value:
            upper_dict.pop(k)
            break;
print("Tags above key",upper_dict)

this worked for me :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM