我正在尝试按python分类。似乎由于某种原因没有分组
使用python 2.7
#!/usr/bin/env python
counts = {}
logfile = open("/tmp/test.out", "r")
for line in logfile:
if line.startswith("20") in line:
seq = line.strip()
substr = seq[0:13]
if substr not in counts:
counts[substr] = 0
counts[substr] += 1
for substr, count in counts.items():
print(count,substr)
我想要下面的输出,按计数分组
6 2019-06-17T00
13 2019-06-17T01
9 2019-06-17T02
7 2019-06-17T03
6 2019-06-17T04
答案 0 :(得分:2)
您的子字符串增量缩进了一个块
for line in logfile:
if line.startswith("20") in line:
seq = line.strip()
substr = seq[0:13]
if substr not in counts:
counts[substr] = 0
# Un-indented below
counts[substr] += 1
# Print output only after loop completes
for substr, count in counts.items():
print(count,substr)
如果子字符串不在count字典中,则只能进行递增操作。
答案 1 :(得分:-1)
counts = {}
logfile = open("/tmp/test.out", "r")
for line in logfile:
if line.startswith("20") in line:
seq = line.strip()
substr = seq[0:13]
if substr not in counts:
counts[substr] = 0
counts[substr] += 1
for substr, count in counts.items():
print(count,substr)
我认为这会起作用