| by YoungTimes | No comments

Python-统计字符串中每个字符的出现频率及其在字符串中位置

1、使用collections.Counter()统计字符串中每个字符出现的频率

collections.counter(iterable-or-mapping)

collections.Counter()接收一个可迭代的实体(Iterable Entity),输出以Entity中的元素为Key,出现频率(Frequency)为Value的统计结果。

如果collections.Counter()的参数为string,该函数的返回结果就是以string中字符为Key,出现频率(Frequency)为Value的字符频率统计结果。

import collections

mainStr = 'This is a sample string and a sample code. It is a very short string. 001122'
 
# Counter is a dict sub class that keeps the characters in string as keys and their frequency as value
frequency = collections.Counter(mainStr)
 
print("Occurrence Count of all characters :")
# Iterate over the dictionary and Print the frequency of each character
for (key, value) in frequency.items():
   print("Occurrence Count of ", key, " is : ", value)

输出结果如下:

Occurrence Count of all characters :
Occurrence Count of  T  is :  1
Occurrence Count of  h  is :  2
Occurrence Count of  i  is :  5
Occurrence Count of  s  is :  8
Occurrence Count of     is :  15
Occurrence Count of  a  is :  6
Occurrence Count of  m  is :  2
Occurrence Count of  p  is :  2
Occurrence Count of  l  is :  2
Occurrence Count of  e  is :  4
Occurrence Count of  t  is :  4
Occurrence Count of  r  is :  4
Occurrence Count of  n  is :  3
Occurrence Count of  g  is :  2
Occurrence Count of  d  is :  2
Occurrence Count of  c  is :  1
Occurrence Count of  o  is :  2
Occurrence Count of  .  is :  2
Occurrence Count of  I  is :  1
Occurrence Count of  v  is :  1
Occurrence Count of  y  is :  1
Occurrence Count of  0  is :  2
Occurrence Count of  1  is :  2
Occurrence Count of  2  is :  2

利用这种方式我们可以字符串中所有字符(包含空格和”.”)的出现次数。如果我们只想统计字符和数字的出现频率以及字符所在的位置,该如何实现呢?

2、利用Regex获得字符串(string)中每个字符(character)的出现频率(Frequency)

# Create a Regex pattern to match alphanumeric characters
regexPattern = re.compile('[a-zA-Z0-9]')

首先我们创建一个正则表达式来匹配字符串和数字字符,然后使用pattern.finditer()在字符串中进行匹配,并记录每个字符出现的次数以及它们出现的频率。

import re

regexPattern = re.compile('[a-zA-Z0-9]')

mainStr = 'This is a sample string and a sample code. It is a very short string. 001122'
 
# Iterate over all the alphanumeric characters in string (that matches the regex pattern)
# While Iterating keep on updating the frequency count of each character in a dictionary
iteratorOfMatchObs = regexPattern.finditer(mainStr)
frequencyOfChars = {}
indexPositions = {}
 
for matchObj in iteratorOfMatchObs:
    frequencyOfChars[matchObj.group()] = frequencyOfChars.get(matchObj.group(), 0) + 1
    indexPositions[matchObj.group()] = indexPositions.get(matchObj.group(), []) + [matchObj.start()]
 
# Iterate over the dictionary and Print the frequency of each character
for (key, value) in frequencyOfChars.items():
    print("Occurrence Count of ", key , " is : ", value , ' & Index Positions : ', indexPositions[key])

程序输出结果:

Occurrence Count of  T  is :  1  & Index Positions :  [0]
Occurrence Count of  h  is :  2  & Index Positions :  [1, 57]
Occurrence Count of  i  is :  5  & Index Positions :  [2, 5, 20, 46, 65]
Occurrence Count of  s  is :  8  & Index Positions :  [3, 6, 10, 17, 30, 47, 56, 62]
Occurrence Count of  a  is :  6  & Index Positions :  [8, 11, 24, 28, 31, 49]
Occurrence Count of  m  is :  2  & Index Positions :  [12, 32]
Occurrence Count of  p  is :  2  & Index Positions :  [13, 33]
Occurrence Count of  l  is :  2  & Index Positions :  [14, 34]
Occurrence Count of  e  is :  4  & Index Positions :  [15, 35, 40, 52]
Occurrence Count of  t  is :  4  & Index Positions :  [18, 44, 60, 63]
Occurrence Count of  r  is :  4  & Index Positions :  [19, 53, 59, 64]
Occurrence Count of  n  is :  3  & Index Positions :  [21, 25, 66]
Occurrence Count of  g  is :  2  & Index Positions :  [22, 67]
Occurrence Count of  d  is :  2  & Index Positions :  [26, 39]
Occurrence Count of  c  is :  1  & Index Positions :  [37]
Occurrence Count of  o  is :  2  & Index Positions :  [38, 58]
Occurrence Count of  I  is :  1  & Index Positions :  [43]
Occurrence Count of  v  is :  1  & Index Positions :  [51]
Occurrence Count of  y  is :  1  & Index Positions :  [54]
Occurrence Count of  0  is :  2  & Index Positions :  [70, 71]
Occurrence Count of  1  is :  2  & Index Positions :  [72, 73]
Occurrence Count of  2  is :  2  & Index Positions :  [74, 75]

3、使用collections.Counter()发现字符串中重复字符(Duplicate Characters)

假设我们有以下字符串:

mainStr = 'This is a sample string and a sample code. It is a very short string. 001122'

我们可以通过collections.Counter()来统计每个字符出现的频率,出现次数超过一次的就是重复字符。

import collections

mainStr = 'This is a sample string and a sample code. It is a very short string. 001122'

listOfDupChars = []
# Counter is a dict sub class that keeps the characters in string as keys and their frequency as value
frequency = collections.Counter(mainStr)
 
# Iterate over the dictionary and Print the frequency of each character
for (key, value) in frequency.items():
   if value > 1:
       listOfDupChars.append(key)
print('Duplicate characters ; ', listOfDupChars)

程序输出结果如下:

Duplicate characters ;  ['h', 'i', 's', ' ', 'a', 'm', 'p', 'l', 'e', 't', 'r', 'n', 'g', 'd', 'o', '.', '0', '1', '2']

发表评论