Search code examples
pythonlogicacronym

How to sort specific string, in the following situation (PYTHON)


I was trying to build a Acronym Shortner (as a beginners project)
LINK:http://pastebin.com/395ig9eC

Explaination:
++ACRONYM BLOCK++

If the user the string variable is set to something like "international Business machines" it return IBM

but in the...

++SORTING BLOCK++

If the user the string variable is set to something like "light amplification by the simulated emission of radiation"

i tried to split the whole sentence by:

 z=string.split(" ")
 l=len(z)

then use this following loop:
'''|SORING BLOCK|'''<

for x in range(0,l,1):
    esc=z[x]
    if (z[x]=="by" or z[x]=="the" or z[x]=="of"):
            esc=z[x+1]


    emp=emp+" "+esc


print emp

But the PROBLEM is the that when there are 2 consecutive exclusion words python messes it up. How do i solve it?


Solution

  • This takes the first letter of each word in the sentence, it ignores words that are excluded, and then puts the letters together using join.

    #Python3
    def make_acronym(sentence):
        excluded_words = ['by', 'the', 'of']
        acronym = ''.join(word[0] for word in sentence.split(' ') if word not in excluded_words)
        return acronym.upper()
    

    Example:

    >>> make_acronym('light amplification by the simulated emission of radiation')
    'LASER'