Home > Blockchain >  How to count occurance of characters in string including variations, like upside-down characters
How to count occurance of characters in string including variations, like upside-down characters

Time:11-08

Sometimes we get text like reversed when people scan documents in reverse, which will look like this:

stri = "1234 ᔭƐᘔІ "

I would like to count occurance of the each number in this cases like.

1 - occured 2 times including reversed one.
2 - occured 2 times including reversed one
3 - occured 2 times including reversed one
4 - occured 2 times including reversed one

I've tried to use normal count like

stri.count('1')

which gives me 1, but I expected 2 including reversed.

Expected output

Number of 2's in str = 2

CodePudding user response:

Firstly, the characters that you are using aren't really flipped but they are some other UNICODE characters. Python, doesn't recognize 1 because it is 1, but it rather recognized it by UNICODES. Therefore, there is no theoretical way to achieve this. However, here's a practical method:

# Create a dict with the matching values
string_and_reverse = {
    "1": ["1", "І"],
    "2": ["2", "ᘔ"],
    "3": ["3", "Ɛ"],
    "4": ["4", "ᔭ"],
} # and so on...

Then, change your code to:

stri= "1234 ᔭƐᘔІ "

def replace(stri:str, value:str):
    literal = string_and_reverse[value] # fetch values to replace
    count = 0
    for l in literal: # iterates through every value in the key
        count = stri.count(l) # count the value and increments it
    return count
print(replace(stri, "1")) # just pass whatever you want to replace in place of "value"

CodePudding user response:

I will give simple funny answer. Deal reversed charcters by reversing them

Install this - Pypi

pip install upsidedown


import upsidedown

strs = "1234 ᔭƐᘔІ "

normal =(strs.count('1'))

flip = (upsidedown.transform('1234 ᔭƐᘔІ'))
flip = (flip.count('1'))

total = flip   normal
print(total)

output

2
  • Related