xmlapicountpython-2.6ietf-restconf

Sort and count words in xml output python script


I'm trying to sort and count every word from the output of the i.find().text command, but I can't find a way to do it without hardcoded filter words in the array.

Used strings:

from xml.etree import ElementTree as ET 

root = ET.fromstring(response.text)

data = root.findall('file.xml')

for i in data:
   print(i.find('file.xml/ssidname').text)

The output of string:

SSID1
SSID1
SSID1
SSID2
SSID3
SSID1
SSID3
SSID2
SSID2

The excepted answer is:

SSID1: 4, SSID2: 3, SSID3: 2

I'm stuck on python 2.6.6 and can't update it, so the idea of using counters can't be used.

If you have any tips, please let me know in the comments. Thanks in advance.


Solution

  • So, I don't know which parts actually work in Python 2.6 but here is a probable solution:

    text = '''SSID1
    SSID1
    SSID1
    SSID2
    SSID3
    SSID1
    SSID3
    SSID2
    SSID2'''
    
    
    counter = {}
    for line in text.split('\n'):
        counter[line] = counter.get(line, 0) + 1
    
    final = dict(sorted(counter.items(), key=lambda x: x[1], reverse=True))
    print(final)