Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Word count
#1
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
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  sys.stdin to do a word count based on user entry Kaltex 3 3,693 Jul-19-2020, 01:54 PM
Last Post: deanhystad
  count unique letters in a word sunny_awesome 4 8,730 Jun-06-2019, 07:15 PM
Last Post: kotter
  Count Letters in a Sentence (without using the Count Function) bhill 3 5,202 Jun-19-2018, 02:52 AM
Last Post: bhill

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020