python - Python:读取文件并将键和值添加到不同行的字典中
问题描述
我对 Python 很陌生,我在完成一项基本上是这样的任务时遇到了麻烦:
#逐行读取WARC文件以识别string1。
#找到string1时,将部分字符串作为键添加到字典中。
#然后继续读取文件识别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: ")
解决方案
目前尚不完全清楚您要做什么,但我会尝试回答。
假设你有一个这样的 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'}
请注意,这种方法一次只将文件的一行加载到内存中,如果文件非常大,这可能很重要。
推荐阅读
- c - 如何打印字符串数组的内容?
- ionic-framework - Ionic Admob 奖励服务器验证
- recursion - 如何在 Clojure 中将有序树转换为命名节点的集合?
- r - 如何将州失业率添加到 R 中的 CPS 数据集?
- ios - 如何使用 Swift 的高阶函数快速解析动态字典数据?
- c# - Entity Framework Core - Fluent API 未配置模型
- python - 我不明白 conv1d、conv2d 的 pytorch 输入大小
- html - CSS页脚不粘并浮动到底部
- c# - MVVMLight C# 如何更改按钮内容
- r - 转换为纯 Markdown 时,不要在 rmarkdown 文档中呈现方程式