【问题标题】:Python file handling / counting amounts in filePython文件处理/计算文件中的数量
【发布时间】: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


【解决方案1】:

不知道如果你像这样缩进错误会发生什么:

但如果那是你的错误所在的地方,我猜这就是原因。这就是你缩进 if-else 的方式:

for key in iplist.keys():
    line = "%-15s = %s" % (key, iplist[key])
    if  key in iplist:
         iplist[key] += 1
    else:
         iplist[key] = 1

【讨论】:

  • 我已经对此进行了排序,但我仍然没有得到任何打印到我的文件或计算相同 IP 地址出现的数字不起作用
  • 调试您的代码,添加打印等,看看出了什么问题
  • 我已经做到了,它没有显示任何问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多