In this example we will show how to get a word from the user and count the number of times the word appears in the file with Python.
Source Code
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
fileName = input("Enter the name of the file with .txt extension: ")
word = input("Please input the word: ")
count = 0
with open(fileName, 'r') as file:
for line in file:
wordList = line.split()
for i in wordList:
if i == word:
count += 1
print("The number of times the word appears: ", count)
Content of test1.txt:
Python is an easy to learn
powerful programming language
Output:
Enter the name of the file with .txt extension: test1.txt
Please input the word: is
The number of times the word appears: 1