Создание и размещение контура счетчика в коде для обработки результатов

#python #xml #loops #counter

#питон #xml #петли #счетчик

Вопрос:

У меня есть некоторый код Python для итерации по большому XML-файлу, чтобы проанализировать определенные результаты в элементе, разделенном запятыми.

В то время как код выводит результаты, мне нужно, чтобы он также подсчитывал результаты. Как мне написать этот цикл в моем текущем коде и где он должен быть размещен? В цикле после моей .split() функции? После?

Мой код:

 #Working python code  #Import libraries import webbrowser  from lxml import etree  #Parses the file to get the tree paths tree = etree.parse('g_d_anime.xml') root = tree.getroot()  #Starts the XPATH using findall to verify the elements inside the tree are right #Might not be necessary, but it's not a bad check to have tree.findall('WorksXML/Work')  #Opens the output file for the results h_file = open("xml_stats.html","w") #Start writing the HTML lines h_file.write("This block shows the producers and genres for this file.") h_file.write('lt;brgt;')  #These loops first split the string, then select the specific value I want to pull out for Producers in root.iter('Producers'):  p = Producers.text.split(',')  for producer in p:  #if you require only to display only 'Nitroplus', put '==' in place of '!='  if producer == 'Aniplex':  print(p) #This prints all the values in the strings  h_file.write('lt;ligt;'   str(producer)   'lt;/ligt;') #This only writes the selected value  h_file.write('lt;brgt;') for Genres in root.iter('Genres'):  g = Genres.text.split(',')  for genre in g:  #if you require only to display only 'Magic', put '==' in place of '!='  if genre == 'Magic':  print(g) #This prints all the values in the strings  h_file.write('lt;ligt;'  str(genre)   'lt;/ligt;') #This only writes the selected value  h_file.write('lt;brgt;')  #Should the counting loop for the above go here? Or within the above loop?  h_file.close()  webbrowser.open_new_tab("xml_stats.html")  

Я не уверен, куда поместить цикл подсчета, или .sum (), или строки счетчика, если это проще. Результаты должны показать что-то вроде:

 Aniplex: 7 Magic: 9  

Файл содержит более 1500 записей, которые структурированы следующим образом:

 lt;WorksXMLgt;  lt;Workgt;  lt;Titlegt;Fullmetal Alchemist: Brotherhoodlt;/Titlegt;  lt;Typegt;TVlt;/Typegt;  lt;Episodesgt;64lt;/Episodesgt;  lt;Statusgt;Finished Airinglt;/Statusgt;  lt;Start_airinggt;2009-4-5lt;/Start_airinggt;  lt;End_airinggt;2010-7-4lt;/End_airinggt;  lt;Starting_seasongt;Springlt;/Starting_seasongt;  lt;Broadcast_timegt;Sundays at 17:00 (JST)lt;/Broadcast_timegt;  lt;Producersgt;Aniplex,Square Enix,Mainichi Broadcasting System,Studio Morikenlt;/Producersgt;  lt;Licensorsgt;Funimation,Aniplex of Americalt;/Licensorsgt;  lt;Studiosgt;Boneslt;/Studiosgt;  lt;Sourcesgt;Mangalt;/Sourcesgt;  lt;Genresgt;Action,Military,Adventure,Comedy,Drama,Magic,Fantasy,Shounenlt;/Genresgt;  lt;Durationgt;24 min. per ep.lt;/Durationgt;  lt;Ratinggt;Rlt;/Ratinggt;  lt;Scoregt;9.25lt;/Scoregt;  lt;Scored_bygt;719706lt;/Scored_bygt;  lt;Membersgt;1176368lt;/Membersgt;  lt;Favoritesgt;105387lt;/Favoritesgt;  lt;Descriptiongt;"In order for something to be obtained, something of equal value must be lost." Alchemy is bound by this Law of Equivalent Exchange—something the young brothers Edward and Alphonse Elric only realize after attempting human transmutation: the one forbidden act of alchemy. They pay a terrible price for their transgression—Edward loses his left leg, Alphonse his physical body. It is only by the desperate sacrifice of Edward's right arm that he is able to affix Alphonse's soul to a suit of armor. Devastated and alone, it is the hope that they would both eventually return to their original bodies that gives Edward the inspiration to obtain metal limbs called "automail" and become a state alchemist, the Fullmetal Alchemist. Three years of searching later, the brothers seek the Philosopher's Stone, a mythical relic that allows an alchemist to overcome the Law of Equivalent Exchange. Even with military allies Colonel Roy Mustang, Lieutenant Riza Hawkeye, and Lieutenant Colonel Maes Hughes on their side, the brothers find themselves caught up in a nationwide conspiracy that leads them not only to the true nature of the elusive Philosopher's Stone, but their country's murky history as well. In between finding a serial killer and racing against time, Edward and Alphonse must ask themselves if what they are doing will make them human again... or take away their humanity.  lt;/Descriptiongt;  lt;/Workgt; ... lt;/WorksXMLgt;  

Я знаю, что петля должна выглядеть примерно так:

 for pr in producer:  pr = 0  if pr in producer:  producer[pr] = producer[pr]   1  else:  producer[pr] = 1  

Если у кого-нибудь есть лучший способ написать это, пожалуйста, поделитесь.

Комментарии:

1. Ваша петля для пиара в продюсере не имеет смысла. Опишите, чего вы пытаетесь достичь

2. @DarkKnight Я пытался выяснить, нужно ли записывать цикл так, как если бы он проходил по вновь извлеченным данным, следовательно, отдельно, или я мог бы интегрировать его в цикл, который я уже построил, чтобы извлечь выбранные данные из строк.

Ответ №1:

Поскольку вы хотите считать Aniplex и Magic только, вы должны поместить его в if блок, а затем после циклов записать его в файл:

 aniplex_count = 0 magic_count = 0  for Producers in root.iter("Producers"):  p = Producers.text.split(",")  for producer in p:  if producer == "Aniplex":  aniplex_count  = 1  h_file.write(  "lt;ligt;"   str(producer)   "lt;/ligt;"  )  h_file.write("lt;brgt;") for Genres in root.iter("Genres"):  g = Genres.text.split(",")  for genre in g:  if genre == "Magic":  magic_count  = 1  h_file.write(  "lt;ligt;"   str(genre)   "lt;/ligt;"  )  h_file.write("lt;brgt;")  h_file.write(f"lt;h2gt;Aniplex: {aniplex_count}lt;/h2gt;") h_file.write(f"lt;h2gt;Magic: {magic_count}lt;/h2gt;")  

Комментарии:

1. Это работает, спасибо!

2. @SassyG Добро пожаловать, счастливого кодирования! 🙂