python读取配置文件并添加字典中,Python:读取文件并从不同的行向字典添加键和值...

I'm very new to Python and I'm having trouble working on an assignment which basically is like this:

#Read line by line a WARC file to identify string1.

#When string1 found, add part of the string as a key to a dictionary.

#Then continue reading file to identify string2, and add part of string2 as a value to the previous key.

#Keep going through file and doing the same to build the dictionary.

I can't import anything so it's causing me a bit of trouble, especially adding the key, then leaving the value empty and continue going through the file to find string2 to be used as value.

I've started thinking something like saving the key to an intermediate variable, then going on to identify the value, add to an intermediate variable and finally build the dictionary.

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: ")

解决方案

Your idea with storing the key to an intermediate value is good.

I also suggest using the following snippet to iterate over the lines.

with open(filename, "rb") as file:

lines = file.readlines()

for line in lines:

print(line)

To create dictionary entries in Python, the dict.update() method can be used.

It allows you to create new keys or update values if the key already exists.

d = dict() # create empty dict

d.update({"key" : None}) # create entry without value

d.update({"key" : 123}) # update the value

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值