解析大型压缩xml文件,python

发布于 2024-08-13 05:16:16 字数 386 浏览 11 评论 0原文

file  = BZ2File(SOME_FILE_PATH)
p = xml.parsers.expat.ParserCreate()
p.Parse(file)

下面的代码尝试解析用 bz2 压缩的 xml 文件。不幸的是,它失败并显示一条消息:

TypeError: Parse() argument 1 must be string or read-only buffer, not bz2.BZ2File

有没有办法动态解析压缩的 bz2 xml 文件?

注意p.Parse(file.read()) 在这里不是一个选项。我想解析一个大于可用内存的文件,所以我需要一个流。

file  = BZ2File(SOME_FILE_PATH)
p = xml.parsers.expat.ParserCreate()
p.Parse(file)

Here's code that tries to parse xml file compressed with bz2. Unfortunately it fails with a message:

TypeError: Parse() argument 1 must be string or read-only buffer, not bz2.BZ2File

Is there a way to parse on the fly compressed bz2 xml files?

Note: p.Parse(file.read()) is not an option here. I want to parse a file which is larger than available memory, so I need to have a stream.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

以为你会在 2024-08-20 05:16:16

只需使用 p.ParseFile(file) 而不是 p.Parse(file) 即可。

Parse() 接受一个字符串,ParseFile() 接受一个文件句柄,并根据需要读取数据。

参考: http://docs.python.org/库/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile

Just use p.ParseFile(file) instead of p.Parse(file).

Parse() takes a string, ParseFile() takes a file handle, and reads the data in as required.

Ref: http://docs.python.org/library/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile

美人迟暮 2024-08-20 05:16:16

使用 .read()file 对象上以字符串形式读取整个文件,然后将其传递给 Parse

file  = BZ2File(SOME_FILE_PATH)
p = xml.parsers.expat.ParserCreate()
p.Parse(file.read())

Use .read() on the file object to read in the entire file as a string, and then pass that to Parse?

file  = BZ2File(SOME_FILE_PATH)
p = xml.parsers.expat.ParserCreate()
p.Parse(file.read())
可是我不能没有你 2024-08-20 05:16:16

你能传入一个 mmap() 的文件吗?这应该负责自动分页文件的所需部分,并避免内存溢出。当然,如果expat构建了一个解析树,它仍然可能会耗尽内存。

http://docs.python.org/library/mmap.html

内存映射文件对象的行为类似于字符串和文件对象。然而,与普通字符串对象不同,它们是可变的。您可以在大多数需要字符串的地方使用 mmap 对象;例如,您可以使用 re 模块来搜索内存映射文件。

Can you pass in an mmap()'ed file? That should take care of automatically paging the needed parts of the file in, and avoid memory overflow. Of course if expat builts a parse tree, it might still run out of memory.

http://docs.python.org/library/mmap.html

Memory-mapped file objects behave like both strings and like file objects. Unlike normal string objects, however, these are mutable. You can use mmap objects in most places where strings are expected; for example, you can use the re module to search through a memory-mapped file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文