我收到了学校的作业,我必须创建一个函数,该函数接收一个字符串,并将字符串中每个单词的第一个字母的连接作为首字母缩写词返回。返回应该类似于 " the first letter in word number {counter} is {letter}"
,其中 {counter}
是单词在给定字符串中的位置,{letter}
是单词的第一个字母。最后,我必须连接以下格式 " the Acronym for the text given is {acronym}"
,其中 {acronym}
是文本的首字母缩写词,它是文本中给出的每个单词的第一个字母的连接。
这是我目前所做的:
def Acronym_Creator(text:str()):
text= 'Hello World I Need Help'
if text != '':
for word in range(len(text.split())):
Counter=0
Counter= Counter+word+1
print ( 'The first letter in word number {Counter} is ')
到目前为止,这只是用于计算单词在给定文本中的位置。我不知道如何连接属于该位置的单词,以便我可以继续然后创建首字母缩写词。
答案 0 :(得分:0)
这里:
def acronym(string):
str_lst = string.split()
acronym = ""
for i in str_lst: # go through all the string elements in our list
acronym += i[0].capitalize() # add the character as 0th position in that string, also you might want to capitalize that letter(if not already).
return acronym
String = "Hello World I Need Help"
print(acronym(String))
答案 1 :(得分:0)
试试这个:
def acronym(text):
words = text.split(' ')
acro = ''
for i in range(len(words)):
print('The first letter in word number {} is {}'.format(i+1, words[i]))
acro += words[i][0].upper()
print('The acronym is {}'.format(acro))
text = 'Hello World this is some text input'
acronym(text)
输出是
The first letter in word number 1 is Hello
The first letter in word number 2 is world
The first letter in word number 3 is this
The first letter in word number 4 is is
The first letter in word number 5 is some
The first letter in word number 6 is text
The first letter in word number 7 is input
The acronym is HWTISTI
答案 2 :(得分:0)
我将为此使用正则表达式库。
有效词的识别:
import re
def acronymizer(string: str):
words = re.findall(pattern=r'\b([A-Za-z]{1}\w*)', string=string)
[print(f"The First letter in {w} is {w[0]}") for w in words]
acronym = ''.join([w[0].upper() for w in words])
print(f"acronym is: {acronym}")
return acronym
String = "Hello World I Need Help !"
print(acronymizer(String))