Python Forum
Count & Sort occurrences of text in a file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Count & Sort occurrences of text in a file
#1
ALL:
I have an ASCII text file that contains First and Last names of a phone list.
Each full name is on a newline.
I need a new list generated that is sorted by the number of occurrences these names appear in the text file.

for example:
the file names.txt contains:
bill smith
joe williams
bill smith
jane doe
joe williams
bill smith

the final list should look like this:
bill smith (3)
joe williams (2)
jane doe (1)

All the examples I see online break the text into a single letter list, which I DON'T WANT!

Thanks in advance for your help.
Reply
#2
No list literal in Python can look like desired “final list”.

What have you tried? Please provide code which does “single letter list” and maybe we can help.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
from collections import Counter, defaultdict

f = open('phonebook.tmp', "r")
if f.mode == "r":
    text = f.read()


freqword = defaultdict(list)
for word, freq in Counter(text).items():
    freqword[freq].append(word)

# print in order of occurrence (with sorted list of words)
for freq in sorted(freqword):
    print('count {}: {}'.format(freq, sorted(freqword[freq])))
Reply
#4
you overcomplicate things
from collections import Counter
 
with open('dupes.csv', "r") as f:
    for name, name_count in Counter(f).items():
        print(f'{name.strip()}:{name_count}')
Output:
bill smith:3 joe williams:2 jane doe:1
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
That's GREAT, but how can I sort the final list according to the number of occurrences?
Reply
#6
The list's sort method or the sorted function take an argument called key that lets you specify a function to be used to obtain the value for each item to be used for sorting.
Reply
#7
(Sep-06-2020, 01:54 PM)ndc85430 Wrote: That's GREAT, but how can I sort the final list according to the number of occurrences?
you can use most_common() method of Counter:
Quote:Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered in the order first encountered:

from collections import Counter
  
with open('dupes.csv', "r") as f:
    for name, name_count in Counter(f).most_common():
        print(f'{name.strip()}:{name_count}')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
That did the trick. Thank you guys for all your help.
I'm a python newbie, but I understand most of the syntax, especially when i see an example for the first time.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,111 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Row Count and coloumn count Yegor123 4 1,321 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  How to sort .csv file test log which item first fail and paint color SamLiu 24 4,839 Sep-03-2022, 07:32 AM
Last Post: Pedroski55
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,311 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,652 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  How to perform DESC table sort on dates stored as TEXT type. hammer 7 2,190 Mar-15-2022, 01:10 PM
Last Post: hammer
  Converted Pipe Delimited text file to CSV file atomxkai 4 6,949 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  all i want to do is count the lines in each file Skaperen 13 4,816 May-23-2021, 11:24 PM
Last Post: Skaperen
  Sort data from JSON file Dummy_in_programming 2 2,436 Jan-04-2021, 06:17 PM
Last Post: deanhystad
  [split] How to convert the CSV text file into a txt file Pinto94 5 3,322 Dec-23-2020, 08:04 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020