Python Forum
Word count - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Word count (/thread-32911.html)



Word count - vanjoe198 - Mar-15-2021

Hello everyone,

I am having trouble with my homework for school and would like someone to guide me in the right direction to get this assignment done. My problem to solve is to read from a file and count how many word occurrences there are in the whole file.
def searchText ():
    print("Please enter a word that will be used to search a text file")
    word = str(input())
    textFile = open('c:\\python\\assignment8\\assignment8.txt', "r")
    data = textFile.read()
    count = 0
    currentWord = ""
    dataSplit = data.split()

    for i in range(1,1000):
        currentWord == i
        print(currentWord)
        if (currentWord == word):
            count == count + 1
        else:
            continue

    print (count)
searchText ()
My thought process so far is that I would like to split the lines into individual words. My text file consists of 1000 words to be checked.

Currently when I run the script it will ask me what word I would like to search for in the text and then my screen is filled with blank lines.

Thanks


RE: Word count - BashBedlam - Mar-16-2021

In python,

for word in dataSplit :
will iterate over every word in the data, so...

def searchText ():
	print("Please enter a word that will be used to search a text file")
	search_word = input()
	textFile = open ('assignment8.txt', "r")
	data = textFile.read()
	dataSplit = data.split ()
	count = 0
	for word in dataSplit :
		if word == search_word :
			count = count + 1
	print (count)

searchText ()
will count every occurrence of the search word. You almost had it.