Python Forum
Extending my text file word count ranker and calculator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extending my text file word count ranker and calculator
#5
A class example,here is not filename or most_common Hard-coded in code.
Now could this be changed in the function version to,but this is a class example how to do it
from collections import Counter
import re

class WordCounter:
    def file_read(self, file_name):
        with open(file_name) as f:
            self.text = f.read().lower()

    @property
    def word_count(self):
        wordlist = self.text.split()
        print(f"A total of {len(wordlist)} words can be found inside this text file.")

    def rank_words(self, count_amount: int) -> int:
        '''Count most common word in a text'''
        words = re.findall('\w+', self.text)
        top_10 = Counter(words).most_common(count_amount)
        for word,count in top_10:
            print(f'{word:<4} {"-->":^4} {count:>4}')
Use class:
>>> text = WordCounter()

>>> text.file_read('Alice.txt')
>>> text.word_count
A total of 29465 words can be found inside this text file.

>>> text.rank_words(5)
the  -->  1818
and  -->   940
to   -->   809
a    -->   690
of   -->   631
Reply


Messages In This Thread
RE: Extending my text file word count ranker and calculator - by snippsat - Jan-19-2019, 02:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Extending list doesn't work as expected mmhmjanssen 2 208 May-09-2024, 05:39 PM
Last Post: Pedroski55
  Replace a text/word in docx file using Python Devan 4 3,724 Oct-17-2023, 06:03 PM
Last Post: Devan
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,169 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Row Count and coloumn count Yegor123 4 1,394 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  For Word, Count in List (Counts.Items()) new_coder_231013 6 2,695 Jul-21-2022, 02:51 PM
Last Post: new_coder_231013
  find some word in text list file and a bit change to them RolanRoll 3 1,584 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  python-docx regex: replace any word in docx text Tmagpy 4 2,313 Jun-18-2022, 09:12 AM
Last Post: Tmagpy
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,749 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Converted Pipe Delimited text file to CSV file atomxkai 4 7,104 Feb-11-2022, 12:38 AM
Last Post: atomxkai
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,563 Aug-12-2021, 04:25 PM
Last Post: palladium

Forum Jump:

User Panel Messages

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