如何将每句话的首字母大写?

12 投票
15 回答
41813 浏览
提问于 2025-04-18 00:57

我正在尝试写一个程序,让每个句子的第一个字母变成大写。到目前为止,我写的代码是这样的,但我不知道怎么把句子之间的句号加回来。例如,如果我输入:

hello. goodbye

那么输出结果是

Hello Goodbye

但是句号就消失了。

string=input('Enter a sentence/sentences please:')
sentence=string.split('.')
for i in sentence:
    print(i.capitalize(),end='')

15 个回答

2
x = 'hello. goodbye. and how are you doing.'
print( '. '.join(map(lambda s: s.strip().capitalize(), x.split('.'))))

# Hello. Goodbye. And how are you doing. 

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

3

也许可以这样做:

print('.'.join(i.capitalize() for i in sentence))
4

你可以使用:

In [25]: st = "this is first sentence. this is second sentence. and this is third. this is fourth. and so on"

In [26]: '. '.join(list(map(lambda x: x.strip().capitalize(), st.split('.'))))
Out[26]: 'This is first sentence. This is second sentence. And this is third. This is fourth. And so on'

In [27]:
7

你可以使用正则表达式。

定义一个正则表达式,用来匹配句子的第一个单词:

import re
p = re.compile(r'(?<=[\.\?!]\s)(\w+)')

这个正则表达式包含一个正向前查找的断言 (?<=...),它会匹配一个句号 .、问号 ? 或感叹号 !,后面跟着一个空格字符 \s。接下来是一个组,用来匹配一个或多个字母数字字符 \w+。实际上,它是在匹配句子结束后的下一个单词。

你可以定义一个函数,让这个正则表达式匹配到的对象变成大写,然后把这个函数传给 sub()

def cap(match):
    return(match.group().capitalize())

p.sub(cap, 'Your text here. this is fun! yay.')

你可能还想为另一个正则表达式做同样的事情,这个正则表达式用来匹配字符串开头的单词:

p2 = re.compile(r'^\w+')

或者通过组合它们,让原来的正则表达式变得更难读:

p = re.compile(r'((?<=[\.\?!]\s)(\w+)|(^\w+))')
13

你可以使用 nltk来进行句子分割

#!/usr/bin/env python3
import textwrap
from pprint import pprint
import nltk.data # $ pip install http://www.nltk.org/nltk3-alpha/nltk-3.0a3.tar.gz
# python -c "import nltk; nltk.download('punkt')"

sent_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
text = input('Enter a sentence/sentences please:')
print("\n" + textwrap.fill(text))
sentences = sent_tokenizer.tokenize(text)
sentences = [sent.capitalize() for sent in sentences]
pprint(sentences)

输出结果

Enter a sentence/sentences please:
a period might occur inside a sentence e.g., see! and the sentence may
end without the dot!
['A period might occur inside a sentence e.g., see!',
 'And the sentence may end without the dot!']

撰写回答