【发布时间】:2012-01-07 18:44:15
【问题描述】:
我是一个 Python 新手,我试图解析一个文件来制作一个内存分配表。我的输入文件格式如下:
48 bytes allocated at 0x8bb970a0
24 bytes allocated at 0x8bb950c0
48 bytes allocated at 0x958bd0e0
48 bytes allocated at 0x8bb9b060
96 bytes allocated at 0x8bb9afe0
24 bytes allocated at 0x8bb9af60
我的第一个目标是制作一个表格来计算特定数量的字节分配实例。换句话说,我对上述输入的期望输出是这样的:
48 bytes -> 3 times
96 bytes -> 1 times
24 bytes -> 2 times
(目前,我不关心内存地址)
由于我使用的是 Python,我认为使用字典来做这件事是正确的方法(基于大约 3 小时的 Python 教程阅读时间)。这是个好主意吗?
在尝试使用字典执行此操作时,我决定将字节数设为“键”,将计数器设为“值”。我的计划是在每次出现键时递增计数器。截至目前,我的代码sn-p如下:
# Create an empty dictionary
allocationList = {}
# Open file for reading
with open("allocFile.txt") as fp:
for line in fp:
# Split the line into a list (using space as delimiter)
lineList = line.split(" ")
# Extract the number of bytes
numBytes = lineList[0];
# Store in a dictionary
if allocationList.has_key('numBytes')
currentCount = allocationList['numBytes']
currentCount += 1
allocationList['numBytes'] = currentCount
else
allocationList['numBytes'] = 1
for bytes, count in allocationList.iteritems()
print bytes, "bytes -> ", count, " times"
这样,我在“has_key”调用中遇到语法错误,这让我怀疑是否甚至可以将变量用作字典键。到目前为止,我看到的所有示例都假定密钥是预先可用的。就我而言,只有在解析输入文件时才能获取密钥。
(请注意,我的输入文件可能有数千行,有数百个不同的键)
感谢您提供的任何帮助。
【问题讨论】:
-
我看到你引用了'numBytes',所以,你总是指的是常量
-
你在
if allocationList.has_key('numBytes')和else之后的行中省略了冒号——应该是语法错误
标签: python