0

我想编写一个代码来读取和打开一个文本文件并告诉我有多少“。” (句号)它包含

我有这样的事情,但我现在不知道该怎么办?!

f = open( "mustang.txt", "r" )
    a = []
    for line in f:
4

6 回答 6

2
with open('mustang.txt') as f:
    s = sum(line.count(".") for line in f)
于 2012-07-27T02:45:53.010 回答
1

即使使用正则表达式

import re
with open('filename.txt','r') as f:
    c = re.findall('\.+',f.read())
    if c:print len(c)
于 2012-07-27T03:00:48.070 回答
1

我会这样做:

with open('mustang.txt', 'r') as handle:
  count = handle.read().count('.')

如果您的文件不是太大,只需将其作为字符串加载到内存中并计算点数。

于 2012-07-27T02:45:05.307 回答
1
with open('mustang.txt') as f:
    fullstops = 0
    for line in f:
        fullstops += line.count('.')
于 2012-07-27T02:45:25.987 回答
1

这将起作用:

with open('mustangused.txt') as inf:
    count = 0
    for line in inf:
        count += line.count('.')

print 'found %d periods in file.' % count
于 2012-07-27T02:45:27.717 回答
1

假设您的文件绝对没有太大的危险,以至于不会导致您的计算机内存不足(例如,在用户可以选择任意文件的生产环境中,您可能不希望使用此方法):

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
于 2012-07-27T02:46:00.040 回答