Skip to content Skip to sidebar Skip to footer

How To Create Different Files For Each Time A Function Is Performed On An Item In A For Loop?

So building off of a code below that a community member here helped me fine-tune to create a function that takes a dictionary value from a text file and looks then looks through th

Solution 1:

I am not sure, if I understood your requirement correctly. Now what this code does is, with respect to the attribute given in the speaking-basic.txt, find the attributes in the parsed xml's. If the attribute name and its values match in both speaking-basic.txt and the xml's, then output it to a file with the name of the Speaker.

Check if this is what you were looking for, maybe I might not have understood it correctly. If so, please provide a clear understanding of the expected output with screenshots or samples.

import csv
import glob
import ast
from os.path import isfile
from lxml import etree

deflook_for_speaker_in_files(speakerAttrib):
    speakerDict = ast.literal_eval(speakerAttrib)
    file_name = str(speakerDict.values()[0]).format()
    l_file_exists = Falseif isfile(file_name + ".csv"):
        l_file_exists = True
    c = csv.writer(open(file_name + ".csv","a"))
    ifnot l_file_exists:
        c.writerow(["Name", "Filename", "Text"])
    lparser = etree.XMLParser(recover=True)
    for cr_file in glob.iglob('parsed/*.xml'):
        try:
          tree = etree.parse(cr_file,parser=lparser)
          for node in tree.iter('speaking'):
             if node.keys() == speakerDict.keys():
                if node.values() == speakerDict.values():
                    c.writerow([node.attrib, cr_file, node.text])
                else:
                    continueelse:
                 continueexcept:
          print"bad string " + cr_file
          raisedefmain():
    withopen("speaking-basic.txt","r") as speaker_list:
        for x in speaker_list:
            print x
            look_for_speaker_in_files(x)
if __name__ == "__main__":
    main()

Post a Comment for "How To Create Different Files For Each Time A Function Is Performed On An Item In A For Loop?"