Brooke
Brooke

Reputation: 19

Making acronym for every airport in Python list?

How do I create a new column, and write acronyms for each respective airport record using Python on a csv file?

I have a csv file of airports and I want the names of the airports to be in acronym form so that I can display them on a map more compactly, with the airport symbol showing what it is.

An example would be this sample list:

['Bradley Sky Ranch', 'Fire Island Airport', 'Palmer Municipal Airport']

into this: ['B.S.R', 'F.I.A.', 'P.M.A.']

Next, how would you put the '.' period punctuation between each acronym letter?

I think it would be + "." + or something with ".".join?

Lastly, a benefit would be if there is a way to get rid of the word 'Airport' so that every acronym doesn't end with 'A'?

For example, something like .strip 'Airport'... but it's not the main goal.

The numbered list below shows examples of code I have, but I have no coherent solution. So please take only what makes sense, and if it doesn't I would like to learn more effective syntax!

[The original airport data is from the ESRI Living Atlas.] I have a new field/column called 'NameAbbrev' which I want to write the acronyms into, but I did this in ArcPro which contains essentially a black-box interface for calculating new fields.

Sidenote: Why am I posting to SO and not GeoNet if this is map related? Please note that my goal is to use python and am not asking about ArcPy. I think the underlying principle is python-based for operating on a csv file (whereas ArcPy would be operating on a featureclass and you would have to use ESRI-designated functions). And SO reaches a wider audience of python experts.

1) So far, I have come across how to turn a string into an acronym, which works great on a single string, not a list: Creating acronyms in Python

acronym = "".join(word[0] for word in test.upper().split())

2) and attempted to split the items in a list, or how to do readlines on a csv file based on an example (not mine): Attribute Error: 'list' object has no attribute 'split'

def getQuakeData():
filename = input("Please enter the quake file: ")
# Use with to make sure the file gets closed
with open(filename, "r") as readfile:
    # no need for readlines; the file is already an iterable of lines
    # also, using generator expressions means no extra copies
    types = (line.split(",") for line in readfile)
    # iterate tuples, instead of two separate iterables, so no need for zip
    xys = ((type[1], type[2]) for type in types)
    for x, y in xys:
        print(x,y)

getQuakeData()

3) Also, I have been able to use pandas to print out just the column of airport names into a list:

import pandas
colnames = ['OBJECTID', 'POLYGON_ID', 'POLYGON_NM', 'NM_LANGCD', 'FEAT_TYPE', 'DETAIL_CTY', 'FEAT_COD', 'NAME_FIX', 'ORIG_FID', 'NameAbbrev']
data = pandas.read_csv(r'C:\Users\...\AZ_Airports_table.csv', names=colnames)

names = data.NAME_FIX.tolist()
print(names)

#Here is a sample of the list of airport names/print result.
#If you want a sample to demo guidance you could use these names:
#['NAME_FIX', 'Bradley Sky Ranch', 'Fire Island Airport', 'Palmer Municipal Airport', 'Kodiak Airport', 'Nome Airport', 'Kenai Municipal Airport', 'Iliamna Airport', 'Sitka Airport', 'Wrangell Airport', 'Sand Point Airport', 'Unalaska Airport', 'Adak Airport', 'Homer Airport', 'Cold Bay Airport']

4) I've also been able to use search cursor and writerow in the past, but I don't know how exactly to apply these methods. (unrelated example):

with open(outCsv, 'wb') as ouputCsv:  
writer = csv.writer(outputCsv)  
writer.writerow(fields)  # writes header containing list of fields  
rows = arcpy.da.SearchCursor(fc, field_names=fields)  
for row in rows:  
    writer.writerow(row)  # writes fc contents to output csv  
del rows

5) So, I have pieces, but I don't know how to put them all together or if they even fit together. This is my Frankenstein monster of a solution, but it is wrong because it is trying to look at each column!

def getAcronym():
filename = r'C:\Users\...\AZ_Airports_table.csv'
# Use with to make sure the file gets closed
with open(filename, "r") as readfile:
    # no need for readlines; the file is already an iterable of lines
    # also, using generator expressions means no extra copies
    airport = (line.split(",") for line in readfile)
    # iterate tuples, instead of two separate iterables, so no need for zip
    abbreviation = "".join(word[0] for word in airport.upper().split())
    # could also try    filter(str.isupper, line)
print(abbreviation)

getAcronym()

Is there a simpler way to combine these ideas and get the acronym column I want? Or is there an alternative way?

Upvotes: 1

Views: 929

Answers (3)

Chris
Chris

Reputation: 22983

This can be done quite simply using a list comprehension, str.join, and filter:

>>> data = ['Bradley Sky Ranch', 'Fire Island Airport', 'Palmer Municipal Airport']
>>> ['.'.join(filter(str.isupper, name)) for name in data]
['B.S.R', 'F.I.A', 'P.M.A']

A more robust approach which doesn't rely on words in the name being capitalized:

>>> data = ['Bradley Sky Ranch', 'Fire Island Airport', 'Palmer Municipal Airport']
>>> ['.'.join(word[0] for word in name.split()) for name in data]
['B.S.R', 'F.I.A', 'P.M.A']
>>> data = ['bradley sky ranch', 'fire island airport', 'palmer municipal airport']
>>> ['.'.join(filter(str.isupper, name)) for name in data] # fails
['', '', '']
>>> ['.'.join(word[0] for word in name.split()) for name in data] # works
['b.s.r', 'f.i.a', 'p.m.a']
>>>

Upvotes: 2

Enrique Bruzual
Enrique Bruzual

Reputation: 493

Shortest answer

You can iterate over each string in the list, by using a for loop, then you can add each result to a new list. It could be turned into a function if you desire.

airports = ['Bradley Sky Ranch', 'Fire Island Airport', 'Palmer Municipal Airport']

air_acronyms = []
for airport in airports:
    words = airport.split()
    letters = [word[0] for word in words]
    air_acronyms.append(".".join(letters))

print(air_acronyms)

output

['B.S.R', 'F.I.A', 'P.M.A']

Upvotes: 1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

I don't know and actually not properly understood what you want but as far as I understand you want to generate the acronym of your list of strings with the first character of every word. So what about my below solution with couple of loops? You can use list comprehension or filter or other cool functions of python to achieve what you want further. Let me know if I miss anything.

input = ['Bradley Sky Ranch', 'Fire Island Airport', 'Palmer Municipal Airport']

output = []
for i in input:
    j =  i.split(' ')
    res = ''
    for k in j:
        res+= k[0] + '.'
    output.append(res)
print(output)  

Output:

['B.S.R.', 'F.I.A.', 'P.M.A.']

Upvotes: 0

Related Questions