I would like to count the number of special characters [^&*$]
appearing in a paragraph using python. Can anyone help me to do this in succinctly? I don't want to use for loop condition.
To use the function, enter =LEN(cell) in the formula bar and press Enter. In these examples, cell is the cell you want to count, such as B1. To count the characters in more than one cell, enter the formula, and then copy and paste the formula to other cells.
The code snippet for this is given as follows. for(int i = 0; str[i] != '\0'; i++) { if(str[i] == c) count++; } cout<<"Frequency of alphabet "<<c<<" in the string is "<<count; The program to find the frequency of all the alphabets in the string is given as follows.
There are 33 characters classified as ASCII Punctuation & Symbols are also sometimes referred to as ASCII special characters.
Counter
makes a set of all the characters giving an upper bound to the number of iterations.
Given a string of text
:
import string
import collections as ct
special_chars = string.punctuation
sum(v for k, v in ct.Counter(text).items() if k in special_chars)
Replace specials_chars
with whatever characters you wish to count.
This might be a duplicate but you can use regex re.sub
and len i.e Replace all the word characters \w
with ''
so you end up with non word characters or special characters.
import re
x = "asdfklsdf#$&^#@!"
new = re.sub('[\w]+' ,'', x)
Output : #$&^#@!
len(new)
7
In case you want to count only those characters then
new = re.sub('[^\^&*$]+' ,'', x)
re.findall
...If you have an input string of:
para = "hello #123 ^@"
you can use re.findall
to get a list of matches to a regex
. So if we use the regex
: '[\w]`, we can get a list of all non special chars in the string. Simply then subtract the length of that list from the length of the original string to get the number of special chars:
specialChars = len(para) - len( re.findall('[\w]', para) )
which returns 3
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With