简体   繁体   中英

Creating a python table from key/counters text file

Text file example

<counter name="abcb">70324360</counter>
<counter name="efghij">1094</counter>
<counter name="klm">0</counter>

I want to create a function that will return the counter number(1094) when I call the counter name(efghij). I don't actually know where to start with that text file.

You may use xml module, which is very closed to your file structure:

s = '''
<counter name="abcb">70324360</counter>
<counter name="efghij">1094</counter>
<counter name="klm">0</counter>'''

import xml.etree.ElementTree as ET

tree = ET.fromstring('<root>' + s + '</root>')

def get_counter(name):
    for node in tree.iter('counter'):
        if node.attrib.get('name') == name:
            return node.text

Usage:

get_counter('klm')

'0'

In case you're reading the source from file, just change to this and wrap with a <root> node:

with open('your_file.txt', 'r') as f:
    s = f.read()

tree = ET.fromstring('<root>' + s + '</root>')
...

As a side note : fromstring() will fail if it hasn't got a root node, which you can simply wrap it before parsing.

Instead of a function, you can create a dict to hold the counters. Read the text file ('file.txt' in this case) and use re to extract the data from each line.

import re

counter = {}
re_counter = re.compile(r'name="(\w+)">(\d+)')
for line in open('file.txt'):
    match = re_counter.search(line)
    if match:
        counter[match.group(1)] = match.group(2)
print counter["efghij"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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