Python Forum

Full Version: Word count
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.