对于我的任务,我必须实现fix_capitalization()函数。fix_capitalization()有一个字符串参数,并返回一个更新的字符串,其中句子开头的小写字母被大写字母替换。fix_capitalization()还返回已大写的字母数。在fix_capitalization()函数中调用execute_menu(),然后输出大写字母数,后面跟着编辑的字符串。原文:我们将继续我们在太空中的探索。将会有更多的航天飞机飞行,更多的航天飞机工作人员,当然,还有更多的志愿者,更多的平民,更多的太空教师。一切都没有结束,我们的希望和旅程还在继续!大写字母数:3个编辑文本:我们将继续我们在太空的探索。将会有更多的航天飞机飞行,更多的航天飞机工作人员,当然,还有更多的志愿者,更多的平民,更多的太空教师。一切都没有结束,我们的希望和旅程还在继续!
到目前为止我的代码是:
def fix_capitalization(usr_str):
small_char = usr_str.split('.')
return small_charUsr_str是输入的变量。任何帮助都是非常感谢的。谢谢。
发布于 2022-08-10 04:59:30
您可以使用regex,这样就可以处理多个空格:
import re
usr_str = "we'll continue our quest in space. there will be more shuttle flights and more shuttle crews and, yes; more volunteers, more civilians, more teachers in space. nothing ends here; our hopes and our journeys continue!"
usr_str, n = re.subn("(^|[.])\s*[a-z]", lambda x: x.group(0).upper(), usr_str)
print(usr_str)
print(n)输出:
We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes; more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue!
3从你的角度来看,我可以想到这一点,它只适用于单个空间:
usr_str = usr_str.split('. ')
n = len(usr_str)
print('. '.join([s.capitalize() for s in usr_str])) 发布于 2022-08-10 05:21:55
正如Ash所述,您可以使用regex处理多个空格,对于具有大写计数的单个空间,只要在句点结束后大写,就可以初始化变量并计数。
def fix_capitalization(text):
# Split the text into a list of sentences.
sentences = text.split(". ")
# Initialize a variable to hold the number of capitalized letters.
capitalized = 0
# Loop through the sentences.
for i in range(len(sentences)):
# If the first letter of the sentence is lowercase, capitalize it.
if sentences[i][0].islower():
sentences[i] = sentences[i].capitalize()
capitalized += 1
# Join the sentences back together into a single string.
text = ". ".join(sentences)
# Return the number of capitalized letters and the updated text.
return capitalized, text发布于 2022-08-10 06:17:47
你也可以这样做,也许你会觉得更容易:
usr_str =“我们将在太空中继续我们的探索。将会有更多的航天飞机飞行和更多的航天飞机机组人员,是的;更多的志愿者、更多的平民、更多的空间教师。这里什么都没有结束;我们的希望和旅程还在继续!”
usr_str_nospace = usr_str.replace(". " ,".")
texts = usr_str_nospace.split('.')
texts = [text.capitalize() for text in texts]
user_str_capitalized = ". ".join(texts)
print("Capital Letters: ", sum(1 for c in user_str_capitalized if c.isupper()))
print(user_str_capitalized)https://stackoverflow.com/questions/73300655
复制相似问题