段落的标题案例

时间:2013-06-06 22:44:11

标签: python string python-2.7 for-loop

我正在创建一个马尔可夫链算法。我输出一个叫做句子的变量,里面包含一串句子。我想把句子判刑,所以我写了这个:

for l in range(0, len(sentence)-1):
    if l == 0:
        sentence[l].upper()
    elif sentence[l] == ".":
        sentence[l+2].upper()

这样做,将第一个单词的第一个字母大写。然后,如果它遇到一个句号,则在它之后的两个字符是新句子的开头。但是,我不知道如何改变这句话。这是我尝试过的,但是非法的:

elif sentence[l] == "."
    sentence[l+2] = sentence[l+2].upper()

并且不,sentence.title()将不起作用,因为它会使每个单词标题都为案例。

2 个答案:

答案 0 :(得分:4)

Python已经有.capitalize()方法:

>>> 'this is a sentence.'.capitalize()
'This is a sentence.'

问题是,它不适用于多个句子:

>>> 'this is a sentence. this is another.'.capitalize()
'This is a sentence. this is another.'

它也不能很好地处理空白:

>>> ' test'.capitalize()
' test'
>>> 'test'.capitalize()
'Test'

为了解决这个问题,你可以将句子分开,删除空格,将它们大写,然后将它们重新组合在一起:

>>> '. '.join([s.strip().capitalize() for s in 'this is a sentence. this is another.'.split('.')]).strip()
'This is a sentence. This is another.'

你也可以使用正则表达式,它应该更加通用:

import re

def capitalizer(match):
    return match.group(0).upper()

sentence = 'this is a sentence. isn\'t it a nice sentence? i think it is'
print re.sub(r'(?:^\s*|[.?]\s+)(\w)', capitalizer, sentence)

输出:

This is a sentence. Isn't it a nice sentence? I think it is

答案 1 :(得分:1)

在Python中,

字符串是不可变的。您可以将新字符串再次分配给同一个变量,或将其转换为列表,改变列表,然后再次''.join()

>>> sentence = list("hello. who are you?")
>>> for l in range(0, len(sentence)-1):
...     if l == 0:
...         sentence[l] = sentence[l].upper()
...     elif sentence[l] == ".":
...         sentence[l+2] = sentence[l+2].upper()
...
>>> ''.join(sentence)
'Hello. Who are you?'