Python Forum
The number of occurrences of statistical characters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The number of occurrences of statistical characters
#2
There are special characters that need to be escaped if you want to use them literally. The error comes at the \ which is RegEx own escape char. So the result is (when not escaped) is invalid pattern.

import re, sre_constants
 
patter = [chr(i) for i in range(33,126)]
 
with open("a.txt","r") as file:
    content = file.read()
    for i in patter:
        try:
            result = len(re.findall(r"[%s]" % i,content))
        except sre_constants.error:
            print('error with {}'.format(i))
Output:
error with \ error with ^
change the for body like this
        try:
            result = len(re.findall(r"[%s]" % i,content))
        except sre_constants.error:
            result = len(re.findall(r"[\%s]" % i,content))
        if result != 0:
            print("%s:%d" % (i, result))  
and it work.

That said, note that you also need to escape chars like *, ? or . in order to search for them literally. I will leave this to you
Reply


Messages In This Thread
RE: The number of occurrences of statistical characters - by buran - Dec-10-2017, 06:59 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Find if chain of characters or number Frankduc 4 1,807 Feb-11-2022, 01:55 PM
Last Post: Frankduc
  Count number of occurrences of list items in list of tuples t4keheart 1 2,399 Nov-03-2020, 05:37 AM
Last Post: deanhystad
  Count & Sort occurrences of text in a file oradba4u 7 3,099 Sep-06-2020, 03:23 PM
Last Post: oradba4u
  Translation of R Code to Python for Statistical Learning Course SterlingAesir 2 2,144 Aug-27-2020, 08:46 AM
Last Post: ndc85430
  Remove escape characters / Unicode characters from string DreamingInsanity 5 13,794 May-15-2020, 01:37 PM
Last Post: snippsat
  Counting number of occurrences of a single digit in a list python_newbie09 12 5,566 Aug-12-2019, 01:31 PM
Last Post: perfringo
  Occurrences using FOR and IF cycle P86 2 2,533 Jul-29-2019, 04:37 PM
Last Post: ThomasL
  Split Column Text by Number of Characters cgoldstein 3 3,013 Mar-11-2019, 01:45 PM
Last Post: perfringo
  Printing Easter date occurrences samsonite 8 5,055 Mar-06-2019, 11:49 AM
Last Post: samsonite
  Counting number of characters in a string Drone4four 1 3,461 Aug-16-2018, 02:33 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020