【问题标题】:Python: Reading a file and adding keys and values to dictionaries from different linesPython:读取文件并将键和值添加到不同行的字典中
【发布时间】:2020-09-30 12:44:44
【问题描述】:

我对 Python 很陌生,但我在完成一项基本上是这样的任务时遇到了麻烦:

#逐行读取WARC文件以识别string1。

#找到string1时,将部分字符串作为key添加到字典中。

#然后继续读取文件识别string2,并将string2的一部分作为值添加到之前的key中。

#继续浏览文件并做同样的事情来构建字典。

我无法导入任何东西,所以这给我带来了一些麻烦,尤其是添加键,然后将值留空并继续通过文件查找要用作值的 string2。

我已经开始考虑将键保存到中间变量,然后继续识别值,添加到中间变量并最终构建字典。

def main ():
###open the file
file = open("warc_file.warc", "rb")
filetxt = file.read().decode('ascii','ignore')
filedata = filetxt.split("\r\n")
dictionary = dict()
while line in filedata:
    for line in filedata:
        if "WARC-Type: response" in line:
            break
    for line in filedata:
        if "WARC-Target-URI: " in line:
           urlkey = line.strip("WARC-Target-URI: ")

【问题讨论】:

  • 欢迎来到 Stack Overflow。要获得好的答案,请编辑您的问题以添加您目前获得的代码(请参阅stackoverflow.com/help/how-to-ask)。同时,请注意添加一个空字符串 ("") 作为初始值可能有助于解决部分问题。
  • 你可能想要一个解析一行的函数,而不是检查一堆 if 语句。这可能会有所帮助:docs.python.org/3.8/library/stdtypes.html#str.split
  • 您想在字典中添加的键和值的示例是什么?最终目标是什么?
  • 为什么不使用 WARC 解析库,例如 warcio? WARC 文件通常很大,可能包含二进制内容作为记录有效负载(PDF 文档、图像等)。此外,您要查找的关键字(“WARC-Type: response”)可以作为有效负载的一部分包含在内。试想一下,stackoverflow 被爬取,这个页面被归档在一个 WARC 文件中。
  • @SebastianNagel OP 说他不能导入任何东西,所以我假设外部库已经出来了。许多老师认为让孩子们重新发明轮子是件好事:-)

标签: python dictionary warc


【解决方案1】:

目前尚不完全清楚您要做什么,但我会尝试回答。

假设您有一个这样的 WARC 文件:

WARC-Type: response
WARC-Target-URI: http://example.example
something
WARC-IP-Address: 88.88.88.88

WARC-Type: response
WARC-Target-URI: http://example2.example2
something else
WARC-IP-Address: 99.99.99.99

然后您可以创建一个字典,将目标 URI 映射到 IP 地址,如下所示:

dictionary = dict()

with open("warc_file.warc", "rb") as file:
  urlkey = None
  value = None

  for line in file:
    if b"WARC-Target-URI: " in line:
      assert urlkey is None
      urlkey = line.strip(b"WARC-Target-URI: ").rstrip(b"\n").decode("ascii")

    if b"WARC-IP-Address: " in line:
      assert urlkey is not None
      assert value is None

      value = line.strip(b"WARC-IP-Address: ").rstrip(b"\n").decode("ascii")

      dictionary[urlkey] = value

      urlkey = None
      value = None

print(dictionary)

这将打印以下结果:

{'http://example.example': '88.88.88.88', 'http://example2.example2': '99.99.99.99'}

请注意,这种方法一次只将文件的一行加载到内存中,如果文件非常大,这可能很重要。

【讨论】:

    【解决方案2】:

    您将密钥存储到中间值的想法很好。

    我还建议使用以下 sn-p 来遍历这些行。

    with open(filename, "rb") as file:
        lines = file.readlines()
        for line in lines: 
            print(line)
    

    要在 Python 中创建字典条目,可以使用 dict.update() 方法。 如果键已经存在,它允许您创建新键或更新值。

    d = dict() # create empty dict
    d.update({"key" : None}) # create entry without value
    d.update({"key" : 123}) # update the value
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 2020-04-12
      相关资源
      最近更新 更多