gpt4 book ai didi

python - 读取文件时如何从 Python 中的行分隔符中排除 U+2028?

转载 作者:太空宇宙 更新时间:2023-11-03 15:29:24 26 4
gpt4 key购买 nike

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

最佳答案

我无法在 mac os x 上的 python 2.5、2.6 或 3.0 中复制此行为 - U+2028 始终被视为非端线。您能否更详细地说明您看到此错误的位置?

就是说,这是"file"类的一个子类,它可能会执行您想要的操作:

#/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")

关于python - 读取文件时如何从 Python 中的行分隔符中排除 U+2028?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1105106/

26 4 0