In Python, how do I make an acronym of a given string?
Like, input string:
'First Second Third'
Output:
'FST'
I am trying something like:
>>> for e in x:
print e[0]
开发者_如何学GoBut it is not working... Any suggestions on how this can be done? I am sure there is a proper way of doing this but I can't seem to figure it out. Do I have to use re
?
Try
print "".join(e[0] for e in x.split())
Your loop actually loops over all characters in the string x
. If you would like to loop over the words, you can use x.split()
.
If you want to use capitals only
>>>line = ' What AboutMe '
>>>filter(str.isupper, line)
'WAM'
What about words that may not be Leading Caps.
>>>line = ' What is Up '
>>>''.join(w[0].upper() for w in line.split())
'WIU'
What about only the Caps words.
>>>line = ' GNU is Not Unix '
>>>''.join(w[0] for w in line.split() if w[0].isupper())
'GNU'
Without re
:
>>> names = 'Vincent Vega Jules Winnfield'
>>> ''.join(x[0] for x in names.split())
'VVJW'
If you want to do things the way that is grammatically correct (regardless of locale), use title()
, then filter()
:
acronym = filter(str.isupper, my_string.title())
title()
is pretty awesome; it makes a string titlecased and is correct according to locale.
Now for something a little bit different...
words = "There ain't no such thing as a free lunch."
acronym = ''.join(word[0] for word in words.upper().split())
print acronym
# TANSTAAFL
(TANSTAAFL is a fairly well-know one, BTW).
s = 'First Second Third'
x = s.split(' ')
for e in x:
print e[0]
should do the trick.
Also you could use
re.split('\W')
to split the line/text on non-word characters. This might be a little bit more robust.
This is my suggestion so we can remove words like to, and , of as well as signs like',':
stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', "The"]
Phrase=input("please enter the phrase you need its acronym: ")
acro=""
for i in range(len(stopwords)):
Phrase=Phrase.replace(stopwords[i]+' ',"")
Phrase=Phrase.replace(',',' ')
Phrase=Phrase.upper()
Words=Phrase.split( )
for word in Words:
acro = acro + word[0]
print(acro)
Here's how to do acronym with regular expression, leaving numbers as is:
import re
words = "internet explorer 10"
print re.sub(r"([a-zA-Z])[a-z,A-Z]+\s*",r"\1",words).upper()
IE10
There is a python-based tool for this task, that suggests multiple acronyms, that can be installed via
pip install acronym
Source code repo is here: https://github.com/bacook17/acronym
this is my suggestion
abbr=input("enter:")
list1=abbr.split()
print(list1)
for x in range(0,len(list1)):
print(list1[x][:1],end="")
精彩评论