我的任务是将输入文本转换为首字母缩略词并将其反转。该单词的长度应超过3个字符且不包含,!'?.
等符号。例如,如果我有这句话"That was quite easy?"
,则该函数应返回EQT
到目前为止我已经完成了:
def acr(message):
words = message.split()
if check_length(words) is False:
return "the input long!"
else:
first_letters = []
for word in words:
first_letters.append(word[0])
result = "".join(first_letters)
return reverse(result.upper())
def check(word):
if len(word) > 3:
return False
def check_length(words):
if len(words) > 50:
return False
def rev(message):
reversed_message = message[::-1]
return reversed_message
我的check
功能有问题。如何正确控制单词和符号的长度?
答案 0 :(得分:1)
有点hacky,因为逗号在技术上是一个特殊的角色(但你想要简单易用),但这对你的例子很有效。设置" if"在"声明中的单词"部分。
def acronymize(message):
"""Turn the input text into the acronym and reverse it, if the text is not too long."""
words = message.split()
if check_message_length(words) is False:
return "Sorry, the input's just too long!"
else:
first_letters = []
for word in words:
if len(word) > 3 and word.isalnum()== True or (len(word) > 4 and ',' in word): #satisfies all conditions. Allows commas, but no other special characters.
first_letters.append(word[0])
result = "".join(first_letters)
return reverse(result.upper())
基本上' if'如果你有长度的话> 3个字符和单词是字母数字(然后满足所有条件)OTHERWISE(OR)如果单词旁边有逗号(将有len(单词)+1个字符)并且它将有一个逗号(,),那仍然满足以前的条件,然后填充first_letters列表。
否则,请忽略该词。
这样您甚至不必设置check_word函数。
这会吐出答案
' EQT'
我的代码中还有一些例子:
Input: Holy cow, does this really work??
Output: 'RTDH'
**请注意,它没有包括“牛”这个词。因为它没有超过3个字母。
Input: Holy cows, this DOES work!!
Output: 'DTCH'
**注意,现在的术语“奶牛”#39;被计算,因为它有超过3个字母。
您可以类似地使用'或'添加您想要的任何例外(!,?和。)。格式:
Ex:或(len(word)&gt; 4和&#39;!&#39; in word)或(len(word)&gt; 4和&#39;?&#39; in word)< / p>
唯一的假设是句子在语法上是正确的(因为,它不会有感叹号,后面跟着逗号)。
可以通过列出允许的特殊字符列表并将该列表传递给or子句来进一步清理。
希望有所帮助!
答案 1 :(得分:-1)
re.findall(r'(\w)\w{3,}', sentence)
找到每个至少四个字母的第一个字母
''.join(reversed(re.findall(r'(\w)\w{3,}', sentence))).upper()
如果要忽略非单词字符前面的单词,请使用(\w)\w{3,},?(?:$|\s)
- 这也允许显式使用逗号。
''.join(reversed(re.findall(r'(\w)\w{3,},?(?:$|\s)', sentence))).upper()