Python 段落的标题格

Python 段落的标题格,python,string,python-2.7,for-loop,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() 它的作用是,将第一个单词的第一个字母大写。如果遇到句点,后面两个字符就是新句子的开头。然而,我不知道如何改

我正在创建一个马尔可夫链算法。我输出一个名为句子的变量,它包含一个句子字符串。我想把这句话写下来,所以我写了这个:

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()
不,句子.title()将不起作用,因为它将使每个单词的标题都是大小写。

在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?'

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.'
您也可以使用regex来实现,它应该更加通用:

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

您所描述的不是标题案例。标题大小写表示每个单词都大写。你所描述的只是句子的正确大写。同样值得注意的是,在Python中,按索引进行迭代是一种非常糟糕的方法。迭代值,这种语言就是为此而设计的——它更快、更简单、可读性更好、更灵活。@Lattyware哎呀,我指的是句子大小写。现在修复。请注意,
str.strip()
将去除所有空格,因此这可能会导致句子之间额外的空格丢失-这不太可能是一个问题,但值得注意。正则表达式确实用途广泛。有办法分开吗!然后呢?liek是正则表达式,使用纯python?我能想到的唯一方法就是复制代码并替换“.”,但这似乎很愚蠢。@PhilKurtis:只要将代码改为“.”!?“:中的
elif语句[l],它就会工作。