#!/usr/bin/python
file=open("C:/python27/python operators.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print k, v
|
||||
Use a Context Manager When dealing with something like a file, it's safer to write:
That will automatically handle file closing correctly in case of exceptions and the like. I also find it clearer. Also, why Prefer Generators
Use the tools at your disposal You have:
That's a lot of code for a simple operation. What are you doing here? You're counting the incidence of
Furthermore, we also have
Full solution:
|
|||||
|
You can save this syntax:
Using a It would simplify your code to his:
But actually, the
Note I used And lastly, you don't need to use |
|||
|
re.search('(\w)', file.read());
– A Red Herring 18 hours ago