字符串操作是文本数据分析的关键组成部分之一。在分析文本数据时,我们可能需要计算文本中字符的频率。在这篇文章中,我们将讨论在Python中计算字符串中每个字符出现次数的不同方法。
使用For循环和set()函数来计算字符串中每个字符的出现次数
我们可以使用for循环和 set() 函数来计算字符串中每个字符的出现次数。为此,我们将使用以下步骤。
- 首先,我们将创建一个输入字符串中所有字符的集合。为此,我们将使用
set()函数。set()函数将一个可迭代对象作为其输入参数,并返回该可迭代对象的所有元素的集合。 - 在创建字符集后,我们将使用嵌套的for循环来计算每个字符在字符串中的出现次数。
- 在外层for循环中,我们将遍历该集合的元素。在for循环内部,我们将定义一个变量
countOfChar,并将其初始化为0。 - 然后,我们将使用另一个for循环来迭代输入的字符串。
- 在内部for循环中,如果我们在字符串中找到该集合的当前字符,我们将把
countOfChar增加1。 - 在执行内部for循环后,我们将得到一个字符的计数。我们将使用print语句来打印它。然后,我们将使用外层for循环移动到该集合中的下一个字符。
执行for循环后,字符串中每个字符的出现次数将被打印出来。你可以在下面的例子中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
for element in mySet:
countOfChar = 0
for character in input_string:
if character == element:
countOfChar += 1
print("Count of character '{}' is {}".format(element, countOfChar))
输出。
The input string is: Pythonforbeginners is a great source to get started with Python.
Count of character 'o' is 5
Count of character 'a' is 3
Count of character 'c' is 1
Count of character 'e' is 6
Count of character 'd' is 1
Count of character 't' is 8
Count of character 'r' is 5
Count of character 'y' is 2
Count of character 'n' is 4
Count of character 'u' is 1
Count of character 's' is 4
Count of character 'g' is 3
Count of character 'w' is 1
Count of character '.' is 1
Count of character 'h' is 3
Count of character ' ' is 9
Count of character 'P' is 2
Count of character 'b' is 1
Count of character 'i' is 3
Count of character 'f' is 1
如果你想存储字符的频率,你可以使用一个Python字典。为了存储频率,我们将首先创建一个名为countOfChars 的空字典。
在计算了一个字符的计数后,我们将把该字符作为键,计数作为值添加到字典中。你可以在下面的代码中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
countOfChars = dict()
for element in mySet:
countOfChar = 0
for character in input_string:
if character == element:
countOfChar += 1
countOfChars[element] = countOfChar
print("Count of characters is:")
print(countOfChars)
输出。
The input string is: Pythonforbeginners is a great source to get started with Python.
Count of characters is:
{'s': 4, 'P': 2, 'b': 1, '.': 1, 'd': 1, 'c': 1, 'g': 3, 'r': 5, 'i': 3, 'o': 5, 'u': 1, 'a': 3, 'f': 1, 'e': 6, 'n': 4, 'y': 2, ' ': 9, 'w': 1, 't': 8, 'h': 3}
使用Python中的count()方法计算字符串中每个字符的出现次数
字符串中的count() 方法是用来计算字符串中某个字符的频率。在一个字符串上调用时,count() 方法将一个字符作为其输入参数。执行后,它返回作为输入参数的字符的频率。
为了使用count() 方法计算字符串中每个字符的出现次数,我们将使用以下步骤。
- 首先,我们将使用
set()函数在输入字符串中创建一个字符集。 - 之后,我们将使用for循环遍历该集合的元素。
- 在for循环中,我们将在输入字符串中调用
count()方法,并将该集合的当前元素作为其输入参数。执行后,count()方法将返回集合中当前元素的出现次数。我们将使用print语句来打印该值。
在执行for循环后,所有字符的频率将被打印出来。你可以在下面的例子中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
countOfChars = dict()
for element in mySet:
countOfChar = input_string.count(element)
countOfChars[element] = countOfChar
print("Count of character '{}' is {}".format(element, countOfChar))
输出。
The input string is: Pythonforbeginners is a great source to get started with Python.
Count of character 'e' is 6
Count of character 'n' is 4
Count of character 'a' is 3
Count of character '.' is 1
Count of character 'h' is 3
Count of character 'r' is 5
Count of character 'f' is 1
Count of character 'y' is 2
Count of character 's' is 4
Count of character 't' is 8
Count of character 'w' is 1
Count of character 'i' is 3
Count of character 'd' is 1
Count of character 'g' is 3
Count of character 'u' is 1
Count of character 'c' is 1
Count of character 'o' is 5
Count of character 'P' is 2
Count of character 'b' is 1
Count of character ' ' is 9
你也可以将字符的频率存储在一个字典中,如下图所示。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
countOfChars = dict()
for element in mySet:
countOfChar = input_string.count(element)
countOfChars[element] = countOfChar
print("Count of characters is:")
print(countOfChars)
输出结果。
The input string is: Pythonforbeginners is a great source to get started with Python.
Count of characters is:
{'t': 8, 'o': 5, 'P': 2, 'n': 4, 'f': 1, 'e': 6, 'g': 3, 'c': 1, '.': 1, 's': 4, 'w': 1, 'y': 2, ' ': 9, 'u': 1, 'i': 3, 'd': 1, 'a': 3, 'h': 3, 'r': 5, 'b': 1}
上述方法有很高的时间复杂性。如果字符串中有N个不同的字符,而字符串的长度是M,执行的时间复杂度将是M*N的数量级。因此,如果你要分析成千上万个字符的字符串,不建议使用这些方法。为此,我们可以使用下面几节中讨论的其他方法。
使用Python字典来计算字符串中每个字符的出现次数
python中的字典存储键值对。为了使用字典计算字符串中每个字符的出现次数,我们将使用以下方法。
- 首先,我们将创建一个名为
countOfChars的空字典来存储字符和它们的频率。 - 现在,我们将使用for循环来迭代输入的字符串。
- 在迭代过程中,我们将使用成员操作符检查当前字符是否存在于字典中。
- 如果该字符存在于字典中,我们将把与该字符相关的值增加1,否则,我们将把该字符作为一个键添加到字典中,其相关值为1。
执行for循环后,我们将得到countOfChars 字典中每个字符的计数。你可以在下面的例子中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
countOfChars = dict()
for character in input_string:
if character in countOfChars:
countOfChars[character] += 1
else:
countOfChars[character] = 1
print("The count of characters in the string is:")
print(countOfChars)
输出。
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
{'P': 2, 'y': 2, 't': 8, 'h': 3, 'o': 5, 'n': 4, 'f': 1, 'r': 5, 'b': 1, 'e': 6, 'g': 3, 'i': 3, 's': 4, ' ': 9, 'a': 3, 'u': 1, 'c': 1, 'd': 1, 'w': 1, '.': 1}
你可以使用python try-except块来计算字符串中字符的出现次数,而不是使用 if else 语句。
- 在 for 循环内部,我们将在 try 块中把与字典中当前字符相关的值增加 1。如果该字符不存在于字典中,程序将引发一个 KeyError 异常。
- 在 except 块中,我们将捕获 KeyError 异常。在这里,我们将把这个字符作为一个键分配给 dictionary,其相关值为 1。
在执行for循环后,我们将得到countOfChars dictionary中每个字符的计数。你可以在下面的例子中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
countOfChars = dict()
for character in input_string:
try:
countOfChars[character] += 1
except KeyError:
countOfChars[character] = 1
print("The count of characters in the string is:")
print(countOfChars)
输出。
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
{'P': 2, 'y': 2, 't': 8, 'h': 3, 'o': 5, 'n': 4, 'f': 1, 'r': 5, 'b': 1, 'e': 6, 'g': 3, 'i': 3, 's': 4, ' ': 9, 'a': 3, 'u': 1, 'c': 1, 'd': 1, 'w': 1, '.': 1}
如果我们有一个大的输入字符串,与字符串的长度相比,只有很少的不同字符,那么使用try-except块的方法效果最好。如果输入字符串很小,而且输入字符串的长度与不同字符的总数相比不是很大,那么这个方法就会比较慢。这是由于处理异常是一个昂贵的操作。
如果程序非常频繁地引发KeyError异常,将会降低程序的性能。所以,你应该根据输入字符串的长度和字符串中不同字符的数量来选择使用if-else语句还是try-except块。
你也可以避免同时使用if else语句和try-except块。为此,我们需要使用以下方法。
- 首先,我们将使用
set()函数在原始字符串中创建一个字符集。 - 然后,我们将初始化字典
countOfChars,使用该集合的元素作为键,0作为相关值。 - 现在,我们将使用for循环来迭代输入字符串中的字符。在迭代过程中,我们将把
countOfChars中与当前字符相关的值递增1。
执行for循环后,我们将得到字符串中每个字符出现的次数。你可以在下面的例子中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
countOfChars = dict()
for element in mySet:
countOfChars[element] = 0
for character in input_string:
countOfChars[character] += 1
print("The count of characters in the string is:")
print(countOfChars)
输出。
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
{'d': 1, 'r': 5, 'y': 2, 'a': 3, 'P': 2, 'i': 3, 's': 4, ' ': 9, 'f': 1, '.': 1, 'h': 3, 't': 8, 'g': 3, 'c': 1, 'u': 1, 'e': 6, 'n': 4, 'w': 1, 'o': 5, 'b': 1}
使用collections.Counter()函数计算字符串中每个字符的出现次数
collections模块为我们提供了各种处理集合对象的函数,如list、string、set等。Counter() 函数是这些函数中的一个。它被用来计算一个集合对象中元素的频率。
Counter() 函数将一个集合对象作为其输入参数。执行后,它返回一个集合的Counter对象。Counter对象以字典的形式包含了所有的字符和它们的频率。
要在Python中计算一个字符串中每个字符的出现次数,可以简单地将其传递给Counter() 函数,并打印输出,如下例所示。
from collections import Counter
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
countOfChars = Counter(input_string)
print("The count of characters in the string is:")
print(countOfChars)
输出。
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
Counter({' ': 9, 't': 8, 'e': 6, 'o': 5, 'r': 5, 'n': 4, 's': 4, 'h': 3, 'g': 3, 'i': 3, 'a': 3, 'P': 2, 'y': 2, 'f': 1, 'b': 1, 'u': 1, 'c': 1, 'd': 1, 'w': 1, '.': 1})
使用 Collections.defaultdict()
Collections 模块为我们提供了一个具有增强特性的字典对象。这被称为defaultdict 。如果你试图修改与一个不存在于字典中的键相关的值,defaultdict 对象不会引发 KeyError 异常。相反,它自己创建一个键,然后继续执行语句。
例如,如果在一个简单的字典中没有名为 “Aditya” 的键,而我们进行操作myDict[“Aditya”]+=1 ,程序将遇到 KeyError 异常。另一方面,一个defaultdict 对象将首先在字典中创建键“Aditya” ,并成功地执行上述语句。然而,我们需要帮助 defaultdict 对象创建键的默认值。
defaultdict() 函数接受另一个函数,例如fun1 作为其输入参数。每当defaultdict对象需要创建一个带有默认值的新键时,它就会执行fun1 ,并使用fun1 返回的值作为新键的关联值。在我们的例子中,我们需要让一个字符的默认值为0,我们将把int() 函数作为输入参数传给defaultdict() 函数。
为了使用Python中的defaultdict对象计算字符串中每个字符的出现次数,我们将使用以下步骤。
- 首先,我们将使用
collections.defaultdict()函数创建一个 defaultdict 对象。这里,我们将把int()函数作为输入参数传给defaultdict()函数。 - 然后,我们将使用for循环来迭代输入字符串中的字符。
- 在迭代过程中,我们将不断增加与defaultdict对象中每个字符相关的值。
执行for循环后,我们将得到defaultdict对象中每个字符的计数。你可以在下面的例子中观察到这一点。
from collections import defaultdict
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
countOfChars = defaultdict(int)
for character in input_string:
countOfChars[character] += 1
print("The count of characters in the string is:")
print(countOfChars)
输出。
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
defaultdict(<class 'int'>, {'P': 2, 'y': 2, 't': 8, 'h': 3, 'o': 5, 'n': 4, 'f': 1, 'r': 5, 'b': 1, 'e': 6, 'g': 3, 'i': 3, 's': 4, ' ': 9, 'a': 3, 'u': 1, 'c': 1, 'd': 1, 'w': 1, '.': 1})
结论
在这篇文章中,我们讨论了在python中计算字符串中每个字符出现次数的不同方法。在所有这些方法中,我建议你使用使用集合模块的方法,因为这些是最有效的方法。