所以我有一个100000字的文件。我想知道怎样才能创建一个文件,上面写着:“10282次”“和: 322次”"sadfas222: 1次“
文本文件如下所示:
asdf
jkasdf
the
sadf
asdn
23kl
asdf
qer
f
asdf
r
2
r
fsd
fa
sdf
asd
far2
sdv
as
df
asdf
asdf发布于 2016-08-15 23:09:12
您可以使用collections模块中的Counter来执行此操作:
content = open("textfile.txt").read()
from collections import Counter
c = Counter(content.splitlines())
for x in c.most_common():
print("{}: {} times".format(x[0], x[1]))用法:
In [7]: contet = """asdf
...: jkasdf
...: the
...: sadf
...: asdn
...: 23kl
...: asdf
...: qer
...: f
...: asdf
...: r
...: 2
...: r
...: fsd
...: fa
...: sdf
...: asd
...: far2
...: sdv
...: as
...: df
...: asdf
...: asdf"""
In [8]: from collections import Counter
In [9]: c = Counter(content.splitlines())
In [10]: c.most_common()
Out[10]:
[('asdf', 5),
('r', 2),
('f', 1),
('23kl', 1),
('as', 1),
('df', 1),
('sadf', 1),
('qer', 1),
('sdf', 1),
('jkasdf', 1),
('sdv', 1),
('the', 1),
('2', 1),
('fsd', 1),
('asdn', 1),
('fa', 1),
('asd', 1),
('far2', 1)]并遍历c中的结果:
In [11]: for x in c.most_common():
....: print("{}: {} times".format(x[0], x[1]))
....:
asdf: 5 times
r: 2 times
f: 1 times
23kl: 1 times
as: 1 times
df: 1 times
sadf: 1 times
qer: 1 times
sdf: 1 times
jkasdf: 1 times
sdv: 1 times
the: 1 times
2: 1 times
fsd: 1 times
asdn: 1 times
fa: 1 times
asd: 1 times
far2: 1 timeshttps://stackoverflow.com/questions/38948988
复制相似问题