【问题标题】:Title case for a paragraph段落的标题大小写
【发布时间】:2013-06-03 03:11:35
【问题描述】:

我正在创建一个马尔可夫链算法。我输出了一个名为 sentence 的变量,其中包含一串句子。我想把句子变成大小写,所以我写了这个:

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()

不,sentences.title() 将不起作用,因为它会使每个单词的标题大小写。

【问题讨论】:

  • 你所描述的不是title case。标题大小写意味着每个单词都大写。您所描述的只是句子的正确大写。还值得注意的是,按索引迭代是在 Python 中做任何事情的一种非常糟糕的方式。迭代值,该语言就是为此而设计的——它更快、更容易、更好读、更灵活。
  • @Lattyware 哎呀,我的意思是句子大小写。立即修复。

标签: python string python-2.7 for-loop


【解决方案1】:

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

【讨论】:

  • 请注意,str.strip() 将删除 all 空格,因此这可能会导致句子之间的多余空格丢失 - 这不太可能成为问题,但值得注意。跨度>
  • 正则表达式确实是通用的。有没有办法分开!和 ?像正则表达式一样,用纯python?我能想到的唯一方法是复制代码并替换“。”,但这似乎很愚蠢。
  • @PhilKurtis:只需将您的代码更改为 elif sentence[l] in ".!?": 即可。
【解决方案2】:

字符串在 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?'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2010-11-24
    相关资源
    最近更新 更多