-1

我正在尝试构建一个 Acronym Shortner(作为初学者项目)
链接:http ://pastebin.com/395ig9eC

说明:
++ACRONYM BLOCK++

如果用户将字符串变量设置为“国际商务机器”之类的内容,则返回 IBM

但在...

++SORTING BLOCK++

如果用户将字符串变量设置为“模拟辐射发射的光放大”

我试图通过以下方式拆分整个句子:

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

然后使用以下循环:
'''|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

但问题是当有 2 个连续的排除词时,python 会把它搞砸。我该如何解决?

4

1 回答 1

0

这需要句子中每个单词的第一个字母,它会忽略被排除的单词,然后使用 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()

例子:

>>> make_acronym('light amplification by the simulated emission of radiation')
'LASER'
于 2015-07-22T14:35:24.607 回答