在 Python 中创建首字母缩略词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4355201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:23:18  来源:igfitidea点击:

Creating acronyms in Python

python

提问by user225312

In Python, how do I make an acronym of a given string?

在 Python 中,如何制作给定字符串的首字母缩略词?

Like, input string:

比如,输入字符串:

'First Second Third'

Output:

输出:

'FST'

I am trying something like:

我正在尝试类似的东西:

>>> for e in x:
        print e[0]

But 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?

但它不起作用......关于如何做到这一点的任何建议?我确信有一种正确的方法可以做到这一点,但我似乎无法弄清楚。我必须使用re吗?

采纳答案by Sven Marnach

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().

您的循环实际上会遍历 string 中的所有字符x。如果您想遍历单词,可以使用x.split().

回答by user225312

Without re:

没有re

>>> names = 'Vincent Vega Jules Winnfield'
>>> ''.join(x[0] for x in names.split())
'VVJW'

回答by vkris

s = 'First Second Third'
x = s.split(' ')
for e in x:
    print e[0]

should do the trick.

应该做的伎俩。

回答by brown.2179

Also you could use

你也可以使用

re.split('\W')

re.split('\W')

to split the line/text on non-word characters. This might be a little bit more robust.

在非单词字符上拆分行/文本。这可能会更健壮一点。

回答by martineau

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

(TANSTAAFLis a fairly well-know one, BTW).

TANSTAAFL是一个相当有名的人,顺便说一句)。

回答by kevpie

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.

只有 Caps 字样怎么办。

>>>line = ' GNU is Not Unix '
>>>''.join(w[0] for w in line.split() if w[0].isupper())
'GNU'

回答by Rafe Kettler

If you want to do things the way that is grammatically correct (regardless of locale), use title(), then filter():

如果您想以语法正确的方式(无论语言环境如何)做事,请使用title(),然后filter()

acronym = filter(str.isupper, my_string.title())

title()is pretty awesome; it makes a string titlecased and is correct according to locale.

title()非常棒;它使字符串标题化并且根据语言环境是正确的。

回答by Noam Manos

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"",words).upper()

IE10

IE10