首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python读取warc文件

使用python读取warc文件
EN

Stack Overflow用户
提问于 2016-10-18 11:26:24
回答 2查看 4.1K关注 0票数 1

我想读取一个warc文件,我基于this page写了下面的代码,但是没有打印出来!!

代码语言:javascript
复制
>>import warc
>>f = warc.open("01.warc.gz")
>>for record in f:
    print record['WARC-Target-URI'], record['Content-Length']

然而,当我写下下面的命令时,我得到了结果

代码语言:javascript
复制
>>print f
<warc.warc.WARCFile instance at 0x0000000002C7DE88>

请注意,我的warc文件是Clueweb09 dataset中的一个文件。我提到它是因为this page

EN

回答 2

Stack Overflow用户

发布于 2017-03-17 00:14:15

我和你有同样的问题。

在对模块进行了一些研究之后,我找到了一个解决方案。

尝试使用record.payload.read(),下面是完整的示例:

代码语言:javascript
复制
import warc
f = warc.open("01.warc.gz")
for record in f:
  print record.payload.read()

另外,我可以说你不仅可以读取warc文件,还可以读取wet文件。小骗局是将其重命名为包含.warc的name

亲切的问候

票数 2
EN

Stack Overflow用户

发布于 2018-01-21 21:25:06

首先,WARC,或Web ARChive,是一种网页存档格式。读取warc文件有点麻烦,因为它包含一些特殊的头文件。假设您的warc文件是this format格式的。

您可以使用以下代码为包含元数据和内容的每个记录加载、分析和返回字典。

代码语言:javascript
复制
def read_header(file_handler):
    header = {}
    line = next(file_handler)
    while line != '\n':
        key, value = line.split(': ', 1)
        header[key] = value.rstrip()
        line = next(file_handler)
    return header


def warc_records(path):
    with open(path) as fh:
        while True:
            line = next(fh)
            if line == 'WARC/1.0\n':
                output = read_header(fh)
                if 'WARC-Refers-To' not in output:
                    continue
                output["Content"] = next(fh)
                yield output

您可以按如下方式访问字典:

代码语言:javascript
复制
records = warc_records("<some path>')
>>> next_record = next(records)
>>> sorted(next_record.keys())
['Content', 'Content-Length', 'Content-Type', 'WARC-Block-Digest', 'WARC-Date', 'WARC-Record-ID', 'WARC-Refers-To', 'WARC-Target-URI', 'WARC-Type', 'WARC-Warcinfo-ID']
>>> next_record['WARC-Date']
'2013-06-20T00:32:15Z'
>>> next_record['WARC-Target-URI']
'http://09231204.tumblr.com/post/44534196170/high-res-new-photos-of-the-cast-of-neilhimself'
>>> next_record['Content'][:30]
'Side Effects high res. New pho'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40099000

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档