【发布时间】:2022-08-15 04:09:44
【问题描述】:
此代码用于从文件中读取,然后计算相同 ip 出现的次数并将结果打印到我创建的名为 results.csv 的文件中,它打印到 python 上的 PowerShell,但不打印到文件和计数器没有加起来。
infile = open(\"full_log.txt\",\"r\")
iplist = {} # create an empty dict
item_list = {}
for line in infile:
line = line.strip()
if line:
iplist.setdefault(line, 0) #
iplist[line] += 1 # increment
for key in iplist.keys():
line = \"%-15s = %s\" % (key, iplist[key])
if key in iplist:
# the count is not working
iplist[key] += 1
else:
iplist[key] = 1
print(line) # print uf desired.
item_list = [(k, v) for k, v in infile.items()]
# 2 Sort the list by v
item_list.sort(key=lambda x:x[1], reverse=True)
# it wont print to my file i have made
result_file = open(\"results.csv\", \"w\")
for counter in range(1):
current_pair = item_list[counter]
result_file.write(current_pair[0] + \",\" + str(current_pair[1]) + \"\\n\")
result_file.close()
-
您的代码缺少缩进。请修复它。
-
这是我可以上传的唯一方法抱歉
-
您可以单击edit 链接进行编辑。缩进在这里很重要,因为它决定了你的程序是如何工作的。
-
我在我的代码编辑器上正确缩进了它,就在我上传到这里的时候
-
当然,但是如果您需要帮助,请在此处修复。如果你不这样做,那么你可以保持原样。
标签: file printing counting nothing