【发布时间】:2011-06-17 20:29:20
【问题描述】:
当我有一个 utf-8 编码的字符串时,我遇到了 .isupper() 的问题。我有很多要转换为 xml 的文本文件。虽然文本变化很大,但格式是静态的。所有大写的单词都应该用<title> 标签和其他所有东西<p> 包装。它比这要复杂得多,但这应该足以解决我的问题。
我的问题是这是一个 utf-8 文件。这是必须的,因为最终输出中会有 some 很多非英文字符。或许是时候提供一个简短的例子了:
inputText.txt
简历
培根 ipsum dolor sit amet 条牛排 丁骨鸡,磨碎的圆形 nostrud aute pancetta 火腿飞节 事件 aliqua。多洛尔短腰 前鸡肉,查克鼓槌 ut 汉堡和安杜耶。在产房 eiusmod 里脊肉,排骨 enim 球尖香肠。里脊肉 结果侧翼。临时官 沙朗duis。在薄饼做,ut dolore t-bone sint 猪肉 pariatur 多洛尔鸡练习。诺斯特鲁德 肋眼尾,ut ullamco 鹿肉莫利特 猪排proident consectetur fugiat reprehenderit office 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
【问题讨论】:
-
你使用
str()而不是unicode()有什么原因吗? -
isupper()依赖于 8 位字符串的区域设置;我认为这可能是问题的一部分 -
@tchrist - 根据这个网站,罗马数字字符既不是大写也不是小写,使得 Python 中的 False 结果对于 isupper() 是正确的:fileformat.info/info/unicode/char/216a/index.htm。我没有验证 istitle()
-
看到人们提升可证明是错误的 cmets 是非常了不起的。我的陈述是正确的,正如 Unicode 标准™ 明确规定的那样,它是这件事的 权威来源。 Python 只是弄错了。问题是,这个 bug 什么时候修复?
-
@tchrist:请发布您的错误修复请求的 URL。