python检查utf8字符串是否大写

2024-09-28 21:39:01 发布

您现在位置:Python中文网/ 问答频道 /正文

当我有一个utf-8编码的字符串时,.isupper()有问题。我有很多要转换成xml的文本文件。虽然文本非常可变,但格式是静态的。所有大写的单词都应该用<title>标记和其他任何东西<p>包装。这比这个复杂得多,但这应该足以回答我的问题。

我的问题是这是一个utf-8文件。这是必须的,因为最终输出中会有一些非英语字符。现在可以提供一个简单的例子:

inputText.txt

RÉSUMÉ

Bacon ipsum dolor sit amet strip steak t-bone chicken, irure ground round nostrud aute pancetta ham hock incididunt aliqua. Dolore short loin ex chicken, chuck drumstick ut hamburger ut andouille. In laborum eiusmod short loin, spare ribs enim ball tip sausage. Tenderloin ut consequat flank. Tempor officia sirloin duis. In pancetta do, ut dolore t-bone sint pork pariatur dolore chicken exercitation. Nostrud ribeye tail, ut ullamco venison mollit pork chop proident consectetur fugiat reprehenderit officia ut tri-tip.

期望输出

    <title>RÉSUMÉ</title>
    <p>Bacon ipsum dolor sit amet strip steak t-bone chicken, irure ground round nostrud
       aute pancetta ham hock incididunt aliqua. Dolore short loin ex chicken, chuck drumstick
       ut hamburger ut andouille. In laborum eiusmod short loin, spare ribs enim ball tip sausage.
       Tenderloin ut consequat flank. Tempor officia sirloin duis. In pancetta do, ut dolore t-bone
       sint pork pariatur dolore chicken exercitation. Nostrud ribeye tail, ut ullamco venison
       mollit pork chop proident consectetur fugiat reprehenderit officia ut tri-tip.
   </p>

示例代码

    #!/usr/local/bin/python2.7
    # yes this is an alt-install of python

    import codecs
    import sys
    import re
    from xml.dom.minidom import Document

    def main():
        fn = sys.argv[1]
        input = codecs.open(fn, 'r', 'utf-8')
        output = codecs.open('desiredOut.xml', 'w', 'utf-8')
        doc = Documents()
        doc = parseInput(input,doc)
        print>>output, doc.toprettyxml(indent='  ',encoding='UTF-8')

    def parseInput(input, doc):
        tokens = [re.split(r'\b', line.strip()) for line in input if line != '\n'] #remove blank lines

        for i in range(len(tokens)):
            # THIS IS MY PROBLEM. .isupper() is never true.
            if str(tokens[i]).isupper(): 
                 title = doc.createElement('title')
                 tText = str(tokens[i]).strip('[\']')
                 titleText = doc.createTextNode(tText.title())
                 doc.appendChild(title)
                 title.appendChild(titleText)
            else: 
                p = doc.createElement('p')
                pText = str(tokens[i]).strip('[\']')
                paraText = doc.createTextNode(pText)
                doc.appendChild(p)
                p.appenedChild(paraText)

       return doc

if __name__ == '__main__':
    main()

最终,这是相当直接的,我会接受对我的代码的批评或建议。谁不会呢?尤其是我对str(tokens[i])不满意也许有更好的方法循环遍历字符串列表?

但这个问题的目的是找出检查utf-8字符串是否大写的最有效方法。也许我应该考虑为这个设计一个正则表达式。

请注意,我没有运行这段代码,它可能运行得不太好。我从工作代码中手工挑选了部分,可能输入了错误的内容。提醒我,我会改正的。最后,请注意我没有使用lxml


Tags: indoctitleutfshortstriptokensut