ID: 760

Develop a Python program that reads all the text files under a directory and reprompt top-5 words with the most number of occurrences.

Aligned LLM's Response:

Here ' s a Python program that reads all the text files under a directory and rep rom pts the top - 5 words with the most number of occurr ences : \n ``` python \n import os \n from collections import C ounter \n \n def get _ top _ words ( file _ path ): \n words = [] \n with open ( file _ path , ' r ') as f : \n for line in f : \n words . extend ( line . strip (). split ()) \n return sorted ( Counter ( words ). most _ common ( 5 ), key = lambda x : x [ 1 ], reverse = True ) \n \n def get _ top _ words _ from _ dir ( dir _ path ): \n top _ words = [] \n for filename in os . list dir ( dir _ path ): \n if filename . ends with ('. txt '): \n top _ words . extend ( get _ top _ words ( os . path . join ( dir _ path , filename ))) \n return top _ words \n \n if __ name __ == ' __ main __ ': \n top _ words = get _ top _ words _ from _ dir (' path / to / directory ') \n for word in top _ words : \n print ( word [ 0 ], word [ 1 ]) \n ``` \n This program uses the ` os ` module to list all the files in the directory and the ` Counter ` class from the ` collections ` module to count the occurr ences of each word in the text files . The ` get _ top _ words ` function takes a file path as input and returns a list of tu ples containing the word and its frequency . The ` get _ top _ words _ from _ dir ` function takes a directory path as input and recurs ively calls ` get _ top _ words ` on all the text files in the directory . Finally , the program prints out the top - 5 words with the most number of occurr ences . </s>

Legend: Shifted positions  |  Marginal positions  |  Unshifted positions

Token Distributions

Previous
Home
Next