Python Forum
counting with dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
counting with dictionaries
#1
whenever I execute this counting words with dictionaries program it is not behaving, someone help me pin point the problem, the count function is not working. No error message, so am guessing the logic
import sys
def main():
	if len(sys.argv)<2:
		print('using firstfile for word count')
	else:
		filename=sys.argv[1]
		counters={}
		with open('firstfile.txt','r') as f:
			print(f.read())
			content=f.read()
			words=content.split()
			for word in words:
				word=word.upper()
				if word not in counters:
					counters[word]=1
				else:
					counters[word]+=1
			for word, count in counters.item():
				print(word,count)
if __name__=='__main__':
	main()
Reply
#2
from line #5 I guess you want to use the second command line argument as the file to process. At the same time on line 7 the file name is hard coded and you always process firstfile.txt that is located in the current working directory.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Also, if someone does give a file to process, nothing gets processed. Use the if/else just to get the file name, then do the processing after the if/else, not as part of the else clause. When you do print(f.read()), there is nothing left to read. So content=f.read() gets nothing. And item on line 17 needs to be items.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
(Sep-07-2018, 01:04 PM)ichabod801 Wrote: Also, if someone does give a file to process, nothing gets processed. Use the if/else just to get the file name, then do the processing after the if/else, not as part of the else clause. When you do print(f.read()), there is nothing left to read. So content=f.read() gets nothing. And item on line 17 needs to be items.

this helps, It really disturbed me. Thanks mate

(Sep-07-2018, 08:19 AM)buran Wrote: from line #5 I guess you want to use the second command line argument as the file to process. At the same time on line 7 the file name is hard coded and you always process firstfile.txt that is located in the current working directory.

I was really misusing the sys.argv
Reply


Forum Jump:

User Panel Messages

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