每次在for循环中对一个项目执行一个函数时如何创建不同的文件? [英] How to create different files for each time a function is performed on an item in a for loop?

查看:97
本文介绍了每次在for循环中对一个项目执行一个函数时如何创建不同的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,建立一个下面的代码,这里的一个社区成员帮助我微调创建一个从文本文件中获取字典值的函数,然后查看该值以获取文件列表。这是我将代码添加到同一张表中的所有值。

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

def look_for_speaker_in_files(speakerAttrib):
speakerDict = ast.literal_eval(speakerAttrib)
l_file_exists = False
如果isfile(allspeakers.csv )
l_file_exists = True
c = csv.writer(open(allspeakers.csv,a))
如果不是l_file_exists:
c.writerow([名称,文件名,文本)​​)
lparser = etree.XMLParser(recover = True)
在glob.iglob('parsed / *。xml')中的cr_file:
尝试:
tree = etree.parse(cr_file,parser = lparser)
在tree.iter('speak')中的节点:$ b​​ $ b如果node.keys()== speakerDict.keys )
c.writerow([node.attrib,cr_file,node.text])
else:
继续
除了:
打印坏字符串+ cr_file
raise

def main():
with open(speaking-basic.txt,r)as speaker_list:
for x in speaker_list:
print x
look_for_speaker_in_files(x)
如果__name__ ==__main__:
main()

现在我希望从文本文件中为每个项目创建一个不同的文件,并且只将这些文件中的节点的匹配存储到文本文件中的该项目中。



我尝试了下面的代码,我改变了读取文件的功能,试图让它接受文件名和参数的参数从要搜索的文本文件中的项目。然后我更改了从列表中获取项目的代码,从列表中读取该项目,并获取它创建一个文件名,该文件名是该文件中字典项目的值。

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

def look_for_speaker_in_files(speakerAttrib,file_name):
speakerDict = ast.literal_eval(speakerAttrib)
l_file_exists = False
如果isfile(file_name + .csv):
l_file_exists = True
c = csv.writer(打开(file_name +.csv,a))
打印c
如果不是l_file_exists:
c.writerow([Name,Filename,Text])
lparser = etree.XMLParser(recover = True)
在glob.iglob中的cr_file('parsed / * .xml'):
try:
tree = etree.parse(cr_file,parser = lparser)
在tree.iter('speak')中的节点:$ b​​ $ b如果节点.keys()== speakerDict.keys():
c.writerow([node.attrib,cr_file,node.text])
else:
continue
除了:
打印坏字符串+ cr_file
raise

def main():
with open(speak.txt,r)as speaker_list:
for x in speaker_list:
print x
dictx = ast.literal_eval(x)
valuex = str(dictx.values())。format()
print valuex
look_for_speaker_in_files(x,valuex)
if __name__ ==__main__:
main()

我也试图保持看通过文件函数到相同的单个参数,但是添加一个从该参数中提取文件名的变量,但这也不起作用。

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

def look_for_speaker_in_files( speakerAttrib):
speakerDict = ast.literal_eval(speakerAttrib)
file_name = str(speakerDict.values())。format()
l_file_exists = False
如果isfile(file_name + .csv):
l_f ile_exists = True
c = csv.writer(open(file_name +.csv,a))
如果不是l_file_exists:
c.writerow([Name,Filename ,Text])
lparser = etree.XMLParser(recover = True)
在glob.iglob('parsed / *。xml')中的cr_file:
try:
tree = etree.parse(cr_file,parser = lparser)
在tree.iter('speak')中的节点:$ b​​ $ b如果node.keys()== speakerDict.keys():
c.writerow([node.attrib,cr_file,node.text])
else:
继续
除了:
打印坏字符串+ cr_file
raise

def main():
with open(speaking-basic.txt,r)as speaker_list:
for x in speaker_list:
print x
look_for_speaker_in_files(x)
如果__name__ ==__main__:
main()

虽然这些代码创建的文件,所有我的未来,我看到m只能将它放在文件中,而不是放置在列标题中,或者将xml文件中的所有扬声器放在每个文件中,而不仅仅是放入该函数中的那个。另外我不能得到它没有['']周围的文件名。



我有xml文件功能正在搜索和文本文件我在google链接中找到的值为
https://驱动器。 google.com/open?id=0B7lGA34vOZItREhRbmF6Z3YtTnM



对此的任何帮助都将非常感激,谢谢!

解决方案

如果我正确理解你的要求,我不知道。现在,这个代码所做的是关于在speak-basic.txt中给出的属性,找到解析的xml中的属性。如果属性名称和它的值在speak-basic.txt和xml都匹配,则将其输出到名为Speaker的文件。



检查是否是你正在寻找的,也许我可能没有理解它正确。如果是这样,请使用屏幕截图或样品清楚地了解预期的输出。

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

def look_for_speaker_in_files(speakerAttrib):
speakerDict = ast.literal_eval(speakerAttrib)
file_name = str(speakerDict.values()[0])。format()
l_file_exists = False
如果isfile(file_name +.csv):
l_file_exists = True
c = csv.writer(open(file_name +.csv,a))
如果不是l_file_exists:
c.writerow([Name,Filename,Text ])
lparser = etree.XMLParser(recover = True)
在glob.iglob('parsed / *。xml')中的cr_file:
try:
tree = etree。解析(cr_file,parser = lparser)
在tree.iter('speak')中的节点:$ b​​ $ b如果node.keys()== speakerDict.keys():
如果node.values ()== speakerDict.values():
c.writerow([node.attrib,cr_file,node.text])
else:
继续
else:
继续
除了:
print坏字符串+ cr_file
raise

def main():
with open(speaking-basic.txt,r)as speaker_list:
for x在speaker_list中:
print x
look_for_speaker_in_files(x)
如果__name__ ==__main__:
main()
pre>

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 that value for a list of files. This was the code where I was appending all the values found to the same sheet.

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

def look_for_speaker_in_files(speakerAttrib):
    speakerDict = ast.literal_eval(speakerAttrib)
    l_file_exists = False
    if isfile("allspeakers.csv"):
        l_file_exists = True
    c = csv.writer(open("allspeakers.csv","a"))
    if not 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():
                c.writerow([node.attrib, cr_file, node.text])
             else:
                 continue
        except:
          print "bad string " + cr_file
          raise

def main():
    with open("speaking-basic.txt","r") as speaker_list:
        for x in speaker_list:
            print x
            look_for_speaker_in_files(x)
if __name__ == "__main__":
    main()

Now I am looking to create a different file for each item from the text file, and only deposit the matches for the nodes in the files, to that item from the text file.

I tried the code below, where I altered the function that reads through the files to try to get it to take both the argument for the file name and the argument for the item from the text file to be searched for. I then altered the code that takes the item from the list to both read the item from the list, and get it to create a file name that's the value of the dictionary items in the file.

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

def look_for_speaker_in_files(speakerAttrib,file_name):
    speakerDict = ast.literal_eval(speakerAttrib)
    l_file_exists = False
    if isfile( file_name + ".csv"):
        l_file_exists = True
    c = csv.writer(open( file_name + ".csv","a"))
    print c
    if not 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():
                c.writerow([node.attrib, cr_file, node.text])
             else:
                 continue
        except:
          print "bad string " + cr_file
          raise

def main():
    with open("speaking.txt","r") as speaker_list:
        for x in speaker_list:
            print x
            dictx = ast.literal_eval(x)
            valuex = str(dictx.values()).format()
            print valuex
            look_for_speaker_in_files(x,valuex)
if __name__ == "__main__":
    main()

I also tried to keep the looking through the files function to the same single argument, but adding a variable that came up with the file name from that argument, but that also didn't work.

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

def look_for_speaker_in_files(speakerAttrib):
    speakerDict = ast.literal_eval(speakerAttrib)
    file_name = str(speakerDict.values()).format()
    l_file_exists = False
    if isfile(file_name + ".csv"):
        l_file_exists = True
    c = csv.writer(open(file_name + ".csv","a"))
    if not 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():
                c.writerow([node.attrib, cr_file, node.text])
             else:
                 continue
        except:
          print "bad string " + cr_file
          raise

def main():
    with open("speaking-basic.txt","r") as speaker_list:
        for x in speaker_list:
            print x
            look_for_speaker_in_files(x)
if __name__ == "__main__":
    main()

While these codes create the files, with all my futzing with it I seem to only be able to get it to either put nothing in the files but the column headers, or put all the speakers from the xml files within each one, not just the one I've put into the function. Additionally I can't get it to create the file name without the [''] around it.

I have the xml files the function is searching through and the text file with the values I am looking for at the google link here: https://drive.google.com/open?id=0B7lGA34vOZItREhRbmF6Z3YtTnM

Any help on this would be super appreciated, thank you!

解决方案

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

def look_for_speaker_in_files(speakerAttrib):
    speakerDict = ast.literal_eval(speakerAttrib)
    file_name = str(speakerDict.values()[0]).format()
    l_file_exists = False
    if isfile(file_name + ".csv"):
        l_file_exists = True
    c = csv.writer(open(file_name + ".csv","a"))
    if not 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:
                    continue
             else:
                 continue
        except:
          print "bad string " + cr_file
          raise

def main():
    with open("speaking-basic.txt","r") as speaker_list:
        for x in speaker_list:
            print x
            look_for_speaker_in_files(x)
if __name__ == "__main__":
    main()

这篇关于每次在for循环中对一个项目执行一个函数时如何创建不同的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆