Prof. Dipesh Agrawal



Python Program to Count the Occurrences of a Word in a Text FileThis is a Python Program to count the occurrences of a word in a text file.Problem DescriptionThe program takes a word from the user and counts the number of occurrences of that word in a file.Problem Solution1. Take the file name and the word to be counted from the user.2. Read each line from the file and split the line to form a list of words.3. Check if the word provided by the user and any of the words in the list are equal and if they are, increment the word count.4. Exit.Program/Source CodeHere is source code of the Python Program to count the occurrences of a word in a text file. The program output is also shown below.fname = input("Enter file name: ")word=input("Enter word to be searched:")k = 0?with open(fname, 'r') as f: for line in f: words = line.split() for i in words: if(i==word): k=k+1print("Occurrences of the word:")print(k)Program Explanation1. User must enter a file name and the word to be searched.2. The file is opened using the open() function in the read mode.3. A for loop is used to read through each line in the file.4. Each line is split into a list of words using split().5. Another for loop is used to traverse through the list and each word in the list is compared with the word provided by the user.6. If both the words are equal, the word count is incremented.7. The final count of occurrences of the word is printed.Runtime Test Cases?Case 1:Contents of file: hello world hellohello?Output: Enter file name: test.txtEnter word to be searched:helloOccurrences of the word:3?Case 2:Contents of file: hello world testtest test?Output: Enter file name: test1.txtEnter word to be searched:testOccurrences of the word:4Program 2 –def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return countsprint( word_count('the quick brown fox jumps over the lazy dog.'))Output {'the': 2, 'jumps': 1, 'brown': 1, 'lazy': 1, 'fox': 1, 'over': 1, 'quick': 1, 'dog.': 1} import reimport stringfrequency = {}document_text = open('test.txt', 'r')text_string = document_text.read().lower()match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)?for word in match_pattern:????count = frequency.get(word,0)????frequency[word] = count + 1?????frequency_list = frequency.keys()?for words in frequency_list:????print words, frequency[words]If you run the program, you should get something like the following: ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download