Reputation: 475
I would like to write a code that will read and open a text file and tell me how many "." (full stops) it contains
I have something like this but i don't know what to do now?!
f = open( "mustang.txt", "r" )
a = []
for line in f:
Upvotes: 0
Views: 2470
Reputation: 1498
even with Regular Expression
import re
with open('filename.txt','r') as f:
c = re.findall('\.+',f.read())
if c:print len(c)
Upvotes: 1
Reputation: 19983
Assuming there is absolutely no danger of your file being so large it will cause your computer to run out of memory (for instance, in a production environment where users can select arbitrary files, you may not wish to use this method):
f = open("mustang.txt", "r")
count = f.read().count('.')
f.close()
print count
More properly:
with open("mustang.txt", "r") as f:
count = f.read().count('.')
print count
Upvotes: 1
Reputation: 3429
with open('mustang.txt') as f:
s = sum(line.count(".") for line in f)
Upvotes: 2
Reputation: 143152
This will work:
with open('mustangused.txt') as inf:
count = 0
for line in inf:
count += line.count('.')
print 'found %d periods in file.' % count
Upvotes: 1
Reputation: 2848
with open('mustang.txt') as f:
fullstops = 0
for line in f:
fullstops += line.count('.')
Upvotes: 1
Reputation: 298532
I'd do it like so:
with open('mustang.txt', 'r') as handle:
count = handle.read().count('.')
If your file isn't too big, just load it into memory as a string and count the dots.
Upvotes: 1