我想编写一个代码来读取和打开一个文本文件并告诉我有多少“。” (句号)它包含
我有这样的事情,但我现在不知道该怎么办?!
f = open( "mustang.txt", "r" )
    a = []
    for line in f:
with open('mustang.txt') as f:
    s = sum(line.count(".") for line in f)
即使使用正则表达式
import re
with open('filename.txt','r') as f:
    c = re.findall('\.+',f.read())
    if c:print len(c)
我会这样做:
with open('mustang.txt', 'r') as handle:
  count = handle.read().count('.')
如果您的文件不是太大,只需将其作为字符串加载到内存中并计算点数。
with open('mustang.txt') as f:
    fullstops = 0
    for line in f:
        fullstops += line.count('.')
这将起作用:
with open('mustangused.txt') as inf:
    count = 0
    for line in inf:
        count += line.count('.')
print 'found %d periods in file.' % count
假设您的文件绝对没有太大的危险,以至于不会导致您的计算机内存不足(例如,在用户可以选择任意文件的生产环境中,您可能不希望使用此方法):
f = open("mustang.txt", "r")
count = f.read().count('.')
f.close()
print count
更恰当地说:
with open("mustang.txt", "r") as f:
    count = f.read().count('.')
print count