简体   繁体   English

计算Python中一个文本文件包含多少句点

[英]Count how many full stops a text file contains in Python

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:
with open('mustang.txt') as f:
    s = sum(line.count(".") for line in f)

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. 如果文件不太大,只需将其作为字符串加载到内存中并计算点数即可。

with open('mustang.txt') as f:
    fullstops = 0
    for line in f:
        fullstops += line.count('.')

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

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

even with Regular Expression 即使使用正则表达式

import re
with open('filename.txt','r') as f:
    c = re.findall('\.+',f.read())
    if c:print len(c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM