read from a text file, tally the results and print them out (python)
read from a text file, tally the results and print them out (python)
I am trying to gather a list from a .txt file, tally the results and then print them out like this
Bones found:
Ankylosaurus: 3
Pachycephalosaurus: 1
Tyrannosaurus Rex: 1
Struthiomimus: 2
An eample of the dot text file is
Ankylosaurus
Pachycephalosaurus
Ankylosaurus
Tyrannosaurus Rex
Ankylosaurus
Struthiomimus
Struthiomimus
My current code pulls all the names from the .txt file, except im completely stuck from there
frequency =
for line in open('bones.txt'):
bones = line.split()
print(bones)
Any help please?
3 Answers
3
Using collections.defaultdict
collections.defaultdict
Ex:
from collections import defaultdict
d = defaultdict(int)
with open(filename) as infile: #Open File
for line in infile: #Iterate Each Line
d[line.strip()] += 1
print("Bones found:")
for k, v in d.items():
print(": ".format(k, v))
Output:
Bones found:
Struthiomimus: 2
Pachycephalosaurus: 1
Ankylosaurus: 3
Tyrannosaurus Rex: 1
Store each line as a dictionary key (initialized to 0 if line isn't in dict) and increment the value:
frequency =
for line in open('bones.txt'):
if line not in frequency:
frequency[line] = 0
frequency[line] += 1
for k, v in frequency.items():
print(': '.format(k, v))
After the 'for' line just add 'line = line.rstrip()' it will work.
– kkblue
Aug 21 at 5:10
You can use Counter function from collections library to get this.
from collections import Counter
f=open('bones.txt','r')
ls=f.readlines()
s=dict(Counter(ls))
for k in s.keys():
print (':'.format(k,s[k]))
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Hey, that doesnt seem to be working, its printing is adding numbers to the end for the very last one? - Ankylosaurus 3: Pachycephalosaurus 1: Tyrannosaurus Rex 1: Struthiomimus 1: Struthiomimus1:
– Lachlan
Aug 21 at 4:55