简体   繁体   English

对xml输出python脚本中的单词进行排序和计数

[英]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.我正在尝试对i.find().text命令的输出中的每个单词进行排序和计数,但是如果没有数组中的硬编码过滤器单词,我无法找到一种方法。

Used strings:使用的字符串:

from xml.etree import ElementTree as ET 

root = ET.fromstring(response.text)

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

for i in dot11_oper_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.我被困在python 2.6.6并且无法更新它,因此无法使用使用计数器的想法。

If you have any tips, please let me know in the comments.如果您有任何提示,请在评论中告诉我。 Thanks in advance.提前致谢。

So, I don't know which parts actually work in Python 2.6 but here is a probable solution:所以,我不知道哪些部分在 Python 2.6 中实际有效,但这里有一个可能的解决方案:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM