python - 在 Python 中将句子的开头大写
问题描述
以下代码用于要求用户输入一串句子并且每个句子的开头由函数大写的作业。例如,如果用户输入:'hello. 这些是例句。有三个。输出应该是:'你好。这些是例句。有三个。
我创建了以下代码:
def main():
sentences = input('Enter sentences with lowercase letters: ')
capitalize(sentences)
#This function capitalizes the first letter of each sentence
def capitalize(user_sentences):
sent_list = user_sentences.split('. ')
new_sentences = []
count = 0
for count in range(len(sent_list)):
new_sentences = sent_list[count]
new_sentences = (new_sentences +'. ')
print(new_sentences.capitalize())
main()
此代码有两个问题,我不确定如何更正。首先,它将每个句子打印为一个新行。其次,它在末尾增加了一个额外的句点。使用上面的示例输入,此代码的输出将是:
你好。
这些是例句。
他们三个。。
有没有办法将输出格式化为一行并删除最后一个句点?
解决方案
以下适用于合理干净的输入:
>>> s = 'hello. these are sample sentences. there are three of them.'
>>> '. '.join(x.capitalize() for x in s.split('. '))
'Hello. These are sample sentences. There are three of them.'
如果句号周围有更多不同的空白,您可能必须使用一些更复杂的逻辑:
>>> '. '.join(x.strip().capitalize() for x in s.split('.'))
这将可能是也可能不是您想要的空白标准化。
推荐阅读
- java - java.lang.IllegalStateException: getOutputStream() 已在 jsp 中为此响应调用
- java - 蛮力耗尽内存空间
- ionic-framework - 当键盘可见时,键盘隐藏页脚中的输入字段
- php - “不能使用 Intervention\Image\Facades\Image 作为图像,因为该名称已在使用中”
- php - JQuery - Ajax - 滚动和 setInterval
- javascript - Django,JavaScript:将'null'传递给前端时,JS将其转换为&39;null&39;
- react-native - 反应原生 + SAML + OKTA
- java - 如何使用 Mockito 模拟包括 EntityManager
- mysql - docker-compose mysql 导入失败 - 输入设备不是 TTY
- .net - Is there a way to put compressed file in the same folder from which it compressed the text files?