简体   繁体   中英

How to strip 1 and/or 2 words from field

Novice in python. Trying to display a label in ArcGIS map using python. Have tried several expressions but can't seem to strip the words 'Branch' and/or 'Library' from my field called SITE_NAME . Some values for SITE_NAME are stored as

"[name of city] Branch Library"

and others are

"[name of city] Library"

I don't want my labels to show either of these on the map because it looks too busy. Some of the city names contain the string "Ranch" so those were also getting stripped - for example if the name is "Weston Ranch Branch Library" I only want the label to be "Weston Ranch" or if the name was "Weston Library" only display "Weston." Thanks.

def FindLabel ( [SITE], [SITE_NAME] ):
    return [SITE]+"-"+[SITE_NAME]

You could use two replace statements followed by each other as mentioned in the comments. ie

label = label.replace('Branch Library', '').replace('Library', '')

However if you have more words you want to remove you could create an actual shorten_site_name function that has a set of words to remove:

>>> def shorten_site_name(site_name):
...   words_to_remove = {"Branch", "Library"}
...   return ' '.join(w for w in site_name.split() if w not in words_to_remove)
... 
>>> site_names = ["Weston Ranch Branch Library", "Weston Library"]
>>> new_site_names = list(map(lambda site: shorten_site_name(site), site_names))
>>> new_site_names
['Weston Ranch', 'Weston']

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