问题描述
我是Python的新手,在处理基本上像这样的作业时遇到了麻烦:
#逐行读取WARC文件以识别字符串1。
#找到string1后,将字符串的一部分添加为字典的键。
#然后继续读取文件以标识string2,并将string2的一部分作为值添加到上一个键。
#继续浏览文件并进行同样的操作以构建字典。
我无法导入任何东西,这给我带来了一些麻烦,特别是添加密钥,然后将值保留为空,然后继续遍历文件以查找要用作值的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: ")
解决方法
尚不清楚您要做什么,但我可以回答。
假设您有一个这样的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'}
请注意,这种方法一次只能将文件的一行加载到内存中,如果文件很大,这可能很重要。
,将密钥存储到中间值的想法很好。
我还建议使用下面的代码片段遍历各行。
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