简体   繁体   中英

Counting punctuation marks in a file

Good day site users I have such a problem, when reading the number of commas on a line from a file, the total number of commas taken from previous lines is displayed. How to make it so that for each line a different number of commas was displayed?

f = open("file.txt", "r")
cout = 0
vcout = 0
zap = 0
while 1:
    l = f.readline()
    cout += 1
    zappr = '.' in l
    zappr1 = '?' in l
    zappr2 = '!' in l
    zappr3 = '...' in l
    zappr4 = ',' in l
    zappr5 = ';' in l
    zappr6 = ':' in l
    zappr7 = '-' in l
    zappr8 = '(' in l
    zappr9 = ')' in l
    zappr10 = '"' in l
    if zappr == True or zappr1 == True or zappr2 == True or zappr3 == True or zappr4 == True or zappr5 == True or zappr6 == True or zappr7 == True or zappr8 == True or zappr9 == True or zappr10 == True:
        zap += 1
    print('On line',zap,'punctuation marks')
    if not l:
        break
print('In file',cout-1,'lines')
print('In file',zap+1,'punctuation marks')
f.close()

Outputting punctuation marks on each line

On line 0 punctuation marks
On line 1 punctuation marks
On line 2 punctuation marks
On line 2 punctuation marks
On line 3 punctuation marks
On line 3 punctuation marks
On line 4 punctuation marks
On line 4 punctuation marks

The output here will be different to that suggested in the question but should help with how this could be done:

from string import punctuation

with open('file.txt') as data:
    for i, line in enumerate(map(str.strip, data), 1):
        counter = sum(line.count(p_) for p_ in punctuation)
        print(f'There are {counter} punctuation marks in line {i}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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