Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of special characters [^&$#] appearing in a paragraph

Tags:

python

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.

like image 772
Python Team Avatar asked Sep 18 '17 17:09

Python Team


People also ask

How do I count special characters in Excel?

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.

How do you count special characters in a string in C++?

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.

How many special characters are there?

There are 33 characters classified as ASCII Punctuation & Symbols are also sometimes referred to as ASCII special characters.


3 Answers

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.

like image 69
pylang Avatar answered Oct 24 '22 03:10

pylang


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)
like image 4
Bharath Avatar answered Oct 24 '22 03:10

Bharath


Using 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 :)

like image 2
Joe Iddon Avatar answered Oct 24 '22 03:10

Joe Iddon