我有一个 UTF-8 格式的文件,其中某些行包含 U+2028 行分隔符(http://www.fileformat.info/info/unicode/char/2028/index.htm http://www.fileformat.info/info/unicode/char/2028/index.htm)。当我从文件中读取行时,我不希望将其视为换行符。当我迭代文件或使用 readlines() 时,有没有办法将其从分隔符中排除? (除了将整个文件读入字符串然后按 \n 分割。)谢谢!
我无法在 mac os x 上的 python 2.5、2.6 或 3.0 中重复此行为 - U+2028 始终被视为非结束行。您能更详细地说明您在哪里看到此错误吗?
也就是说,这里是“文件”类的一个子类,它可能会执行您想要的操作:
#/usr/bin/python
# -*- coding: utf-8 -*-
class MyFile (file):
def __init__(self, *arg, **kwarg):
file.__init__(self, *arg, **kwarg)
self.EOF = False
def next(self, catchEOF = False):
if self.EOF:
raise StopIteration("End of file")
try:
nextLine= file.next(self)
except StopIteration:
self.EOF = True
if not catchEOF:
raise
return ""
if nextLine.decode("utf8")[-1] == u'\u2028':
return nextLine+self.next(catchEOF = True)
else:
return nextLine
A = MyFile("someUnicode.txt")
for line in A:
print line.strip("\n").decode("utf8")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)