【问题标题】:How make a function that capitalizes a word at the beginning of a sentence如何制作一个在句子开头大写单词的函数
【发布时间】:2021-10-18 07:10:39
【问题描述】:

这是作业

实现 fix_capilization() 函数。 fix_capilization() 有一个字符串参数并返回一个更新的字符串,其中句子开头的小写字母被替换为大写字母。 fix_capilization() 还返回大写字母的数量。在 print_menu() 函数中调用 fix_capilization(),然后输出大写字母的个数和编辑后的字符串。提示 1:查找并使用 Python 函数 .islower() 和 .upper() 来完成此任务。提示 2:创建一个空字符串并使用字符串连接对字符串进行编辑。

例如: 大写字母数:3

编辑文本:我们将继续我们的太空探索。将有更多的穿梭航班和更多的穿梭人员 是的;更多的志愿者,更多的平民,更多的太空教师。没有什么到此结束;我们的希望和我们的 旅程继续!

这是我的代码

def fix_capitalization(userString):
    capitalCount = 0
    editedString = ""
    for cap in userString.split("."):
        cap = cap.strip(" ").capitalize()
        capitalCount += 1
        editedString += cap + ". "
    return capitalCount, editedString

我很难将它组合在一起。我认为除了句号之外,我还需要添加与其他标点符号的拆分,而当我将它们组合在一起时,它就不会出现正确的结果。如果我添加“。”,它甚至会在带有感叹号的句子上添加一个句号,如果我去掉句号,它只会添加空格并去掉标点符号。我做错了什么?

【问题讨论】:

  • 这能回答你的问题吗? Capitalize the first letter after a punctuation
  • 非常感谢,这确实使它更清楚了!我确实需要能够数出我大写了多少个字母。
  • 您假设所有句子都以句点('.')结束。那太天真了。如果句子的第一个字母已经是大写怎么办?无需转换或计算它

标签: python function split capitalization


【解决方案1】:

这种运动可以是一头猪。
句子总是以句号(句号)和空格结尾吗?
通常,但它也可能以问号或感叹号结尾,或者它是最后一句话,后面没有空格。
您还受限于可以使用的函数和构造返回值的方法。 (我假设他们不希望您使用正则表达式等)

这是一个解决方案的尝试,您可以随意破坏、更改或忽略它。

def fix_capitalization(userString):
    use = ""
    cnt = 0
    tmp = userString.split(". ")
    for i in tmp:
        if any(e in i for e in ["!","?","."]): #  This should handle the final sentence ending in !,? or .
            if i[0].islower(): #  Check if the first character is lower case
                use += i[0].upper() + i[1:] #  Change the first character to upper case and append the rest
                cnt += 1 # Increment the count
            else:
                use += i
        else:
            if i[0].islower():
                use += i[0].upper() + i[1:]
                cnt += 1
            else:
                use += i
            use += ". " #  Add back the split .
    return use, cnt

fixed, cnt = fix_capitalization("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!")
print("Ex: Number of letters capitalized: ", cnt)
print(fixed)

输出:

Ex: Number of letters capitalized:  3
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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2011-01-26
    • 2011-07-20
    • 1970-01-01
    • 2020-03-29
    相关资源
    最近更新 更多