【问题标题】:Read warc file with python用python读取warc文件
【发布时间】:2016-10-18 03:26:24
【问题描述】:

我想读取一个warc文件,我根据this page写了以下代码,但没有打印出来!!

>>import warc
>>f = warc.open("01.warc.gz")
>>for record in f:
    print record['WARC-Target-URI'], record['Content-Length']

但是,当我编写以下命令时,我得到了结果

>>print f
<warc.warc.WARCFile instance at 0x0000000002C7DE88>

请注意,我的 warc 文件是来自 Clueweb09 数据集的文件之一。我提到它是因为this page

【问题讨论】:

  • 您链接到的问题的公认答案似乎有解决方案。你试过了吗?
  • @cco 第一框代码不打印。

标签: python warc


【解决方案1】:

我和你有同样的问题。

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

尝试使用record.payload.read(),这里是完整的例子:

import warc
f = warc.open("01.warc.gz")
for record in f:
  print record.payload.read()

另外,我可以说你不仅可以阅读warc 文件,还可以阅读wet。小秘籍就是把它重命名为name,里面包含.warc

亲切的问候

【讨论】:

    【解决方案2】:

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

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

    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
    

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

    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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多