簡體   English   中英

計算Python中一個文本文件包含多少句點

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

我想編寫一個代碼,將讀取並打開一個文本文件,並告訴我有多少“。”。 (句號)包含

我有這樣的東西,但我現在不知道該怎么辦?

f = open( "mustang.txt", "r" )
    a = []
    for line in f:
with open('mustang.txt') as f:
    s = sum(line.count(".") for line in f)

我會這樣做:

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

即使使用正則表達式

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