0
votes

I'm working with open map data and need to be able to update specific tags based on their values. I have been able to read the tags and even print the specific tags that need to be updated to the console, but I have not been able to get them to update.

I am using elementree and lxml. What I'm looking for specifically is if the first word of the addr:street tag is a cardinality direction (ie North, South, East, West) and the last word of the addr:housenumber tag is NOT a cardinality direction, take the first word from the addr:street tag and move it to be the last word of the addr:housenumber tag.

Edited based on questions below.

Initially I was just calling the code with:

clean_data(OUTPUT_FILE)

I didn't realize that iterparse can't be used to print directly from within the method (which I believe is what you're saying). I had code from a different part of the project I use earlier so I adapted what you wrote what what I had before Here's what I have:

Earlier in the file:

import xml.etree.cElementTree as ET
from collections import defaultdict
import pprint
import re
import codecs
import json

OSM_FILE = "Utah County Map.osm"
OUTPUT_FILE = "Utah County Extract.osm"
JSON_FILE = "JSON MAP DATA.json"

The code in this section of the project:

def clean_data(osm_file, tags = ('node', 'way')):
    context = iter(ET.iterparse(osm_file, events=('end',)))
    for event, elem in context:
        if elem.tag == 'node':
            streetTag, street = getVal(elem, 'addr:street')
            if street is None:  # No "street"
                continue
            first_word = getWord(street, True)
            houseTag, houseNo = getVal(elem, 'addr:housenumber')
            if houseNo is None:  # No "housenumber"
                continue
            last_word = getWord(houseNo, False)
            if first_word in direct_list and last_word not in direct_list:
                streetTag.attrib['v'] = street[len(first_word) + 1:]
                houseTag.attrib['v'] = houseNo + ' ' + first_word

for i, element in enumerate(clean_data(OUTPUT_FILE)):
    print(ET.tostring(context.root, encoding='unicode', pretty_print=True, with_tail=False))

When I'm running this right now I"m getting an error:

TypeError: 'NoneType' object is not iterable

I tried adding in the output code I used earlier for another section of the project, but received the same error. Here's that code for reference as well. (Output file in this code refers to the output of the first stage of data cleaning where I removed multiple invalid nodes).

with open(CLEAN_DATA, 'w') as output:
    output.write('<?xml version="1.0" encoding="UTF-8"?>\n')
    output.write('<osm>\n  ')

    for i, element in enumerate(clean_data(OUTPUT_FILE)):
        output.write(ET.tostring(element, encoding='unicode'))

    output.write('</osm>')

Initial edit was in response to Valdi_bo's question below. Here is a sample from my xml file for reference. Yes I am using both Elementree and lxml since lxml seems to be a subset of elementree. Some of the functions I've called earlier in the program have only worked with one or the other so I'm using both.

<?xml version="1.0" encoding="UTF-8"?>
<osm>
  <node changeset="24687880" id="356682074" lat="40.2799548" lon="-111.6457549" timestamp="2014-08-11T20:33:35Z" uid="2253787" user="1000hikes" version="2">
    <tag k="addr:city" v="Provo" />
    <tag k="addr:housenumber" v="3570" />
    <tag k="addr:postcode" v="84604" />
    <tag k="addr:street" v="Timpview Drive" />
    <tag k="building" v="school" />
    <tag k="ele" v="1463" />
    <tag k="gnis:county_id" v="049" />
    <tag k="gnis:created" v="02/25/1989" />
    <tag k="gnis:feature_id" v="1449106" />
    <tag k="gnis:state_id" v="49" />
    <tag k="name" v="Timpview High School" />
    <tag k="operator" v="Provo School District" />
  </node>
  <node changeset="58421729" id="356685655" lat="40.2414325" lon="-111.6678877" timestamp="2018-04-25T20:23:33Z" uid="360392" user="maxerickson" version="4">
    <tag k="addr:city" v="Provo" />
    <tag k="addr:housenumber" v="585" />
    <tag k="addr:postcode" v="84601" />
    <tag k="addr:street" v="North 500 West" />
    <tag k="amenity" v="doctors" />
    <tag k="gnis:feature_id" v="2432255" />
    <tag k="healthcare" v="doctor" />
    <tag k="healthcare:speciality" v="gynecology;obstetrics" />
    <tag k="name" v="Valley Obstetrics &amp; Gynecology" />
    <tag k="old_name" v="Healthsouth Provo Surgical Center" />
    <tag k="phone" v="+1 801 374 1801" />
    <tag k="website" v="http://valleyobgynutah.com/location/provo-office-2/" />
  </node>
</osm>

In this example the first node would remain unchanged. In the second block the addr:housenumber tag should be changed from 585 to 585 North and the addr:street tag should be changed from North 500 West to 500 West.

1
"I am using elementree and lxml." Are you using both libraries in the same program? - mzjn
"which I believe is what you're saying" Who are you talking to? Stack Overflow is not a traditional discussion forum. Please make sure to provide a minimal reproducible example. Where is the input XML? - mzjn
"lxml seems to be a subset of elementree". It is the other way around: lxml is a superset of ElementTree. lxml supports the same basic API as ElementTree plus many additional features. - mzjn
Good to know, thanks. I'm super new to parsing xml. - xldncr

1 Answers

0
votes

Try the following code:

Functions / global variables:

def getVal(nd, kVal):
    '''
    Get data from "tag" child node with required "k" attribute
    Parameters:
      nd   - "starting" node,
      kVal - value of "k" attribute.
    Results:
      - the tag found,
      - its "v" attribute
    '''
    tg = nd.find(f'tag[@k="{kVal}"]')
    if tg is None:
        return (None, None)
    return (tg, tg.attrib.get('v'))

def getWord(txt, first):
    '''
    Get first / last word from "txt"
    '''
    pat = r'^\S+' if first else r'\S+$'
    mtch = re.search(pat, txt)
    return mtch.group() if mtch else ''

direct_list = ["N", "N." "No", "North", "S", "S.",
    "So", "South", "E", "E.", "East", "W", "W.", "West"]

And the main code:

for nd in tree.iter('node'):
    streetTag, street = getVal(nd, 'addr:street')
    if street is None:  # No "street"
        continue
    first_word = getWord(street, True)
    houseTag, houseNo = getVal(nd, 'addr:housenumber')
    if houseNo is None:  # No "housenumber"
        continue
    last_word = getWord(houseNo, False)
    if first_word in direct_list and last_word not in direct_list:
        streetTag.attrib['v'] = street[len(first_word) + 1:]
        houseTag.attrib['v'] = houseNo + ' ' + first_word

I assume that tree variable holds the entire XML tree.

Edit following the comment as of 22:36:33Z

My code works also in a loop based on iterparse.

Prepare e.g. input.xml file with some root tag and a couple of node elements inside. Then try the following code (with necessary imports, functions and global variables presented above):

context = iter(etree.iterparse('input.xml', events=('end',)))
for event, elem in context:
    if elem.tag == 'node':
        streetTag, street = getVal(elem, 'addr:street')
        if street is None:  # No "street"
            continue
        first_word = getWord(street, True)
        houseTag, houseNo = getVal(elem, 'addr:housenumber')
        if houseNo is None:  # No "housenumber"
            continue
        last_word = getWord(houseNo, False)
        if first_word in direct_list and last_word not in direct_list:
            streetTag.attrib['v'] = street[len(first_word) + 1:]
            houseTag.attrib['v'] = houseNo + ' ' + first_word

As iterparse processes only end events, you don't even need and event == 'end' in the first if.

You neither need initial _, root = next(context) from your code, as context.root points to the whole XML tree.

And now, having the constructed XML tree, you can print it, to see the result:

print(etree.tostring(context.root, encoding='unicode', pretty_print=True,
    with_tail=False))

Notes:

  • The above code has been written written without yielding anything, but it generates a full XML tree, updated according to your needs.
  • As the task is to construct an XML tree, this code does not clear anything. Calls to clear are needed only when you:
    • retrieve some data from processed elements and save it elsewhere,
    • don't need these elements any more.

Now you can reconstruct the above code into a "yielding" variant and use it in your environment (you didn't provide any details how your code sample is called).