如何在Python读取文件时排除U+2028作为行分隔符?

3 投票
5 回答
3652 浏览
提问于 2025-04-15 12:47

我有一个UTF-8编码的文件,其中有些行包含U+2028这个行分隔符字符(http://www.fileformat.info/info/unicode/char/2028/index.htm)。我希望在读取文件的行时,不把它当作换行符。有没有办法在遍历文件或使用readlines()时把它排除在分隔符之外?(除了把整个文件读入一个字符串,然后再用\n来分割。)谢谢!

5 个回答

1

感谢大家的回答。
我想我知道你们为什么可能无法复现这个问题。我刚意识到,如果我在打开文件时进行解码,就会出现这个情况,如下所示:

f = codecs.open(filename, encoding='utf-8')
for line in f:
    print line

如果我先打开文件,然后再逐行解码,行与行之间就不会用u2028分隔:

f = open(filename)
for line in f:
    print line.decode("utf8")

(我在Windows上使用的是Python 2.6。这个文件最开始是UTF16LE格式,然后转换成了UTF8格式)。

这真有意思,我想我以后可能不会太多使用codecs.open了 :-)。

2

我没法重现那个情况,不过这里有个简单的解决办法,就是把读取的结果合并起来,直到它们的结尾不是U+2028这个字符为止。

#!/usr/bin/env python

from __future__ import with_statement

def my_readlines(f):
  buf = u""
  for line in f.readlines():
    uline = line.decode('utf8')
    buf += uline
    if uline[-1] != u'\u2028':
      yield buf
      buf = u""
  if buf:
    yield buf

with open("in.txt", "rb") as fin:
  for l in my_readlines(fin):
    print l
2

我在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")

撰写回答