I have some data in xml that are provided via rss. I want to write a simple script to be able to point the code in the right direction and compare only the tags that i want to check.
The idea is that the different data sources may have the same data in different way. So, I want to be able to check the content of the chosen tags from file or url1 to the decided tags from file or url2.
My code fail, I'm unable to have the file written with the comparison asked. I didn't receive clear errors, but the file doesn't contain the requested output.
import pandas as pd
import requests
import xml.etree.ElementTree as ET
from fuzzywuzzy import fuzz
# Function to compare XML files
def compare_xml_files(file1, file2, tags1, tags2):
# Load XML content from the files
tree1 = ET.parse(file1)
tree2 = ET.parse(file2)
# Initialize a dictionary to store the content and similarity results for each tag
content_and_similarity = {}
# Iterate through each tag in tags1 and find matching tags in tags2
for tag1 in tags1:
for tag2 in tags2:
values1 = [elem.text.strip() if elem.text else "" for elem in tree1.iter(tag=tag1)]
values2 = [elem.text.strip() if elem.text else "" for elem in tree2.iter(tag=tag2)]
similarity_scores = [fuzz.token_set_ratio(val1, val2) > 80 for val1 in values1 for val2 in values2]
content_and_similarity[tag1] = values1
content_and_similarity[tag1 + '_similarity'] = similarity_scores
# Save the results to CSV and Excel files
save_results_to_files(content_and_similarity)
def compare_xml_urls(url1, url2, tags1, tags2):
# Fetch XML content from the URLs
response1 = requests.get(url1)
response2 = requests.get(url2)
tree1 = ET.fromstring(response1.content)
tree2 = ET.fromstring(response2.content)
# Initialize a dictionary to store the content and similarity results for each tag
content_and_similarity = {}
# Iterate through each tag in tags1 and find matching tags in tags2
for tag1 in tags1:
for tag2 in tags2:
values1 = [elem.text.strip() if elem.text else "" for elem in tree1.iter(tag=tag1)]
values2 = [elem.text.strip() if elem.text else "" for elem in tree2.iter(tag=tag2)]
similarity_scores = [fuzz.token_set_ratio(val1, val2) > 80 for val1 in values1 for val2 in values2]
content_and_similarity[tag1] = values1
content_and_similarity[tag1 + '_similarity'] = similarity_scores
# Save the results to CSV and Excel files
save_results_to_files(content_and_similarity)
def save_results_to_files(content_and_similarity):
# Get the desired name for the output file
output_name = input("Enter the desired name for the output file: ")
# Convert content and similarity results to DataFrame
df = pd.DataFrame(content_and_similarity)
# Write the DataFrame to a new CSV file
csv_output_file = output_name + '.csv'
df.to_csv(csv_output_file, index=False)
print("CSV data written to", csv_output_file)
# Write the DataFrame to a new Excel file
excel_output_file = output_name + '.xlsx'
df.to_excel(excel_output_file, index=False)
print("Excel data written to", excel_output_file)
# Ask the user for the choice: XML file or XML URL comparison
choice = input("Enter '1' to compare XML files or '2' to compare XML content from URLs: ")
if choice == '1':
# Compare XML files
file1 = input("Enter the path of XML file 1: ")
file2 = input("Enter the path of XML file 2: ")
tags1 = input("Enter the names of the XML tags in file 1 (separated by commas): ").split(",")
tags2 = input("Enter the names of the XML tags in file 2 (separated by commas): ").split(",")
compare_xml_files(file1, file2, tags1, tags2)
elif choice == '2':
# Compare XML content from URLs
url1 = input("Enter the URL for XML content 1: ")
url2 = input("Enter the URL for XML content 2: ")
tags1 = input("Enter the names of the XML tags in content 1 (separated by commas): ").split(",")
tags2 = input("Enter the names of the XML tags in content 2 (separated by commas): ").split(",")
compare_xml_urls(url1, url2, tags1, tags2)
else:
print("Invalid choice. Please enter '1' or '2'.")
I copy here an extract of the two data structure, to help you teach me something:
Data structure 1
<item>
<kmplusItem:idClip>IT96438242_999376124</kmplusItem:idClip>
<pubDate>Thu, 29 Jun 2023 14:43:00 GMT</pubDate>
<kmplusItem:deliveredDate>Thu, 29 Jun 2023 15:33:29 GMT</kmplusItem:deliveredDate>
<title>
<![CDATA[ IDays Milano Coca Cola 1 – 2 luglio: Tutte le info utili per il concerto (location, parcheggi, ingressi, mappe, orari) ]]>
</title>
<kmplusItem:source>worldmagazine.it</kmplusItem:source>
<kmplusItem:country>IT</kmplusItem:country>
<description>
<![CDATA[ 29 Giugno 20231 LUGLIO 202316:00 Apertura porte 17:30 Nothing But Thieves 19:15 THE BLACK KEYS 21:30 LIAM GALLAGHERORARI BIGLIETTERIA 15:00 Apertura ]]>
</description>
<kmplusItem:fulltext>
...
</kmplusItem:fulltext>
<link>https://cdn.reputation.onclusive.com/t/SQdZApqrl-FNGaJqdcc0e94NnvaTZRlA-pdf-zC/worldmagazine.it_20230629024300</link>
<guid isPermaLink="false">IT96438242_999376124</guid>
<kmplusItem:feeder>review</kmplusItem:feeder>
<kmplusItem:medium>Web</kmplusItem:medium>
<kmplusItem:url>https://www.worldmagazine.it/903045/</kmplusItem:url>
<kmplusItem:sourcetype>General Public</kmplusItem:sourcetype>
<category>
<![CDATA[ Trenord ]]>
</category>
<kmplusItem:readingtimeinminute>7</kmplusItem:readingtimeinminute>
<kmplusItem:listeningtimeinsecond>0</kmplusItem:listeningtimeinsecond>
<kmplusItem:listeningtimeinminute>0</kmplusItem:listeningtimeinminute>
<kmplusItem:reach>101.0</kmplusItem:reach>
<kmplusItem:mediavalueEUR>19.11</kmplusItem:mediavalueEUR>
<kmplusItem:mediavalueUSD>20.9</kmplusItem:mediavalueUSD>
<kmplusItem:mediavalueGBP>16.51</kmplusItem:mediavalueGBP>
</item>
<item>
<kmplusItem:idClip>IT96438242_999371898</kmplusItem:idClip>
<pubDate>Thu, 29 Jun 2023 14:32:00 GMT</pubDate>
<kmplusItem:deliveredDate>Thu, 29 Jun 2023 15:18:46 GMT</kmplusItem:deliveredDate>
<title>
<![CDATA[ FAV_Walking Festival: 1 luglio a Erba il paese dei Licini ]]>
</title>
<kmplusItem:source>gazzettadimilano.it</kmplusItem:source>
<kmplusItem:country>IT</kmplusItem:country>
<description>
<![CDATA[ *	Eventi e ManifestazioniBy redazione-29 Giugno 2023 FacebookTwitterGoogle+PinterestWhatsAppLinkedinEmailPrintTelegramFONDAZIONE ]]>
</description>
<kmplusItem:fulltext>
...
</kmplusItem:fulltext>
<link>https://cdn.reputation.onclusive.com/t/SQdZApqrl-5y9M1Da4kintLRvtfkjw-pdf-zC/gazzettadimilano.it_20230629023200</link>
<guid isPermaLink="false">IT96438242_999371898</guid>
<kmplusItem:feeder>review</kmplusItem:feeder>
<kmplusItem:medium>Web</kmplusItem:medium>
<kmplusItem:url>https://www.gazzettadimilano.it/eventi-e-manifestazioni/fav_walking-festival-1-luglio-a-erba-il-paese-dei-licini/</kmplusItem:url>
<kmplusItem:sourcetype>News</kmplusItem:sourcetype>
<category>
<![CDATA[ Trenord ]]>
</category>
<kmplusItem:readingtimeinminute>2</kmplusItem:readingtimeinminute>
<kmplusItem:listeningtimeinsecond>0</kmplusItem:listeningtimeinsecond>
<kmplusItem:listeningtimeinminute>0</kmplusItem:listeningtimeinminute>
<kmplusItem:reach>77.35</kmplusItem:reach>
<kmplusItem:mediavalueEUR>5.2</kmplusItem:mediavalueEUR>
<kmplusItem:mediavalueUSD>5.69</kmplusItem:mediavalueUSD>
<kmplusItem:mediavalueGBP>4.49</kmplusItem:mediavalueGBP>
</item>
Data structure 2
<item>
<title>Soldi agli agenti delle Locali per avere più sicurezza nelle stazioni</title>
<description>LECCO Stazioni più sicure per pendolari e turisti. Regione Lombardia ha stanziato 30mila euro per gli straordinari agli agenti della Polizia Locale che pattugliano le stazioni delle linee che incrociano a Lecco: la Lecco-Milano via Carnate, la Milano-Lecco via Molteno e la Lecco-Colico. Sotto attenzione ci sono soprattutto le stazioni dei paesi dove non ci sono presidi della Polizia ferroviaria, cioè tutti a parte il capoluogo. Lo spiega il consigliere regionale lecchese di Fratelli d'Italia Giacomo Zamperini, che annuncia la proroga dell'innovativo accordo siglato tra prefettura di Lecco, Trenord e Regione per lo svolgimento di specifici servizi contro vandali, passeggeri violenti, portoghesi che non pagano il biglietto e rapinatori. All'iniziativa partecipano gli agenti delle Locali di Lecco, Airuno, Bellano, Brivio, Bulciago, Calco, Cassago, Cernusco, Civate, Colico, Costa, Dervio, Dorio, Galbiate, La Valletta, Malgrate, Mandello, Merate, Molteno, Montevecchia, Nibionno, Oggiono, Olgiate, Osnago, Rogeno, Santa Maria e Valmadrera. «Un intervento che incrementa la presenza degli operatori delle forze dell'ordine a tutela di chi quotidianamente fruisce delle stazioni e delle aree limitrofe», commenta Giacomo Zamperini. D.D.S. © RIPRODUZIONE RISERVATA</description>
<author/>
<link>https://media.mimesi.com/cacheServer/servlet/CNcacheCopy?file=pdf/202306/29/0291_binpagelcc-05.pdf&authCookie=1334485206</link>
<category domain="newspaper">QN - Il Giorno</category>
<category domain="argument">TRENORD - STAMPA</category>
<category domain="language">italian</category>
<category domain="country">italy</category>
<category domain="typology">quotidiano</category>
<category domain="diffusione-cartacea">18574</category>
<category domain="diffusione-cartacea-digitale">18874</category>
<category domain="tiratura">38963</category>
<category domain="lettori">164000</category>
<category domain="visitatori-medi-giornalieri"/>
<category domain="media-pagine-giornaliere-visitate"/>
<category domain="ascoltatori-medi"/>
<guid>628160672</guid>
<pubDate>2023-06-29 00:00:00.0</pubDate>
<deliveryDate>2023-06-29 00:00:00.0</deliveryDate>
</item>
<item>
<title>Un'estate davvero calda Stop ai treni, ecco i bus</title>
<description>COMO Si annuncia un'estate calda per i pendolari della Como-Lecco fino alla fine di agosto saranno costretti a sostituire il treno col pullman. Negli anni scorsi il disagio era concentrato ad agosto, quando la ferrovia se ne andava letteralmente in vacanza, ma quest'anno il loro sacrificio è legato all'inizio dei lavori di elettrificazione della linea. Un progetto che prevede un investimento di oltre 78 milioni ed è stato inserito dal Governo tra le opere per le Olimpiadi Milano-Cortina, anche se difficilmente sarà concluso in tempo. Fino al 27 agosto sono previsti interventi di manutenzione straordinaria tra le stazioni di Albate e Molteno, nel tratto di 22 chilometri che sarà il primo a essere interessato dall'intervento di elettrificazione. Nelle prossime settimane i tecnici oltre alle manutenzioni ordinarie saranno impegnati a compiere i rilievi sulla linea, le due gallerie e gli 8 cavalcaferrovia che dovranno essere completamente riadattati. «Siamo in attesa di una risposta dall'assessore regionale ai trasporti, ma perlomeno quest'anno ci metteranno a disposizione dei bus che svolgeranno il servizio anche nel mese di agosto - spiega Giovanni Galimberti, portavoce dei pendolari -. Gli orari pubblicati in questi giorni sul sito di Trenord sono abbastanza buoni, anche se a Merone per le coincidenze ci sarà da aspettare una ventina di minuti. La buona notizia è che la linea rimarrà attiva, anche se non è quello che chiedevamo noi. Speriamo riescano a organizzare bus Lecco-Merone in coincidenza col treno che porta a Milano. L'autobus non rappresenta un'alternativa al treno, per coprire il tratto ci mette un'ora in più». La partenza del servizio non è stata delle migliori, tanti pendolari e tra loro diversi studenti impegnati negli esami sono stati costretti a utilizzare l'auto e farsi venire a prendere perché gli autobus hanno effettuato fermate diverse rispetto a quelle indicate sul sito di Trenord. «Qualcuno si è rivolto anche all'infopoint di Cadorna, ma gli operatori hanno fornito le indicazioni che risultavano sul sito, anche se non erano quelle giuste». Roberto Canali</description>
<author/>
<link>https://media.mimesi.com/cacheServer/servlet/CNcacheCopy?file=pdf/202306/29/0291_binpagelcc-06.pdf&authCookie=1335408727</link>
<category domain="newspaper">QN - Il Giorno</category>
<category domain="argument">TRENORD - STAMPA</category>
<category domain="language">italian</category>
<category domain="country">italy</category>
<category domain="typology">quotidiano</category>
<category domain="diffusione-cartacea">18574</category>
<category domain="diffusione-cartacea-digitale">18874</category>
<category domain="tiratura">38963</category>
<category domain="lettori">164000</category>
<category domain="visitatori-medi-giornalieri"/>
<category domain="media-pagine-giornaliere-visitate"/>
<category domain="ascoltatori-medi"/>
<guid>628160674</guid>
<pubDate>2023-06-29 00:00:00.0</pubDate>
<deliveryDate>2023-06-29 00:00:00.0</deliveryDate>
</item>
<item>
The data are provided via two different rss link