如何在python中将html文本的大小写更改为句子大小写

时间:2016-04-26 09:41:33

标签: python html django sentencecase

看到我有一个包含html文本的字符串,我们称之为S。

S = "<b>this is a sentence. and this is one more sentence</b>"

我希望将上面的S转换为以下文本

S = <b>This is a sentence. And this is one more sentence</b>

问题是我可以使用我的函数将任何文本转换为句子,但是当文本包含html时,无法告诉我的函数哪个部分是文本,哪个部分是应该避免的html。 因此当我将S作为我的函数的输入时,它会产生不正确的结果,如下所示

S = <b>this is a sentence. And this is one more sentence</b>

因为它被认为是'&lt;'作为句子的第一个字符,所以它尝试转换'&lt;'变为大写,与'&lt;'相同。

现在我的问题是,如果文本已经以html格式编码,如何在python中将文本转换为句子大小写?而且我不想放弃HTML格式化

1 个答案:

答案 0 :(得分:0)

过于简单化的方法

import xml.etree.ElementTree as ET
S = "<b> This is sentence. and this is one more. </b>"

delim = '. ' 

def convert(sentence):
    return sentence[0].upper() + sentence[1:] + delim


def convert_node(child):
    sentences = child.text
    if sentences:
        child.text = ''
        for sentence in sentences.split(delim):
            if sentence:
                child.text += convert(sentence)
    sentences = child.tail
    if sentences:
        child.tail = ''
        for sentence in sentences.split(delim):
            if sentence:
                child.tail += convert(sentence)
    return child

node = ET.fromstring(S)
S = ET.tostring(convert_node(node))

# gives '<b> This is sentence. And this is one more. </b>'

显然,这不会涵盖所有情况,但如果任务受到足够的限制,它将会起作用。这种方法应该适合您已有的功能。从本质上讲,我认为您需要使用解析器来解析HTML,然后操纵每个html节点的文本值。

如果您不愿意使用解析器,请使用正则表达式。这可能更脆弱,因此您必须更多地限制您的输入。像这样的开始:

>>> split_str = re.split('(</?\w+>|\.)', S)
# split_str is ['', '<b>', 'this is a sentence', '.', ' and this is one more sentence', '</b>', '']

然后,您可以检查拆分字符串中的单词是否以&lt;和&gt;

for i, word in enumerate(split_str):
    if len(word) > 1 and not word.startswith('<') or not word.endswith('>'):
       split_str[i] = convert(word)

S = ' '.join(split_str)