给定例如 string "The organization for health, safety and education"
,我怎么能获得:
Required_Output = OHSE
在输出中,我需要由长度超过三个的单词的第一个字母(大写)组成的字符串。
这是一种使用生成器推导式的方法,首先使用split
,然后upper
如果单词的相应长度为,则取第一个字符的>3
:
s = "The organization for health, safety and education"
''.join(i[0].upper() for i in s.split() if len(i) > 3)
# 'OHSE'
尽管正如@tobias_k 所提到的,更好的选择可能是使用stopwords
. 为此,您可以使用nltk.corpus.stopwords
. 您可以这样做:
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
# {'but', 'wasn', 'during', 'does', 'very', 'at',...
现在将上述内容更改为:
''.join(i[0].upper() for i in s.split() if i.lower() not in stop_words)
# 'OHSE'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句