如何在Python中遍历字符串?

40 投票
10 回答
69326 浏览
提问于 2025-04-11 09:28

举个例子,假设我想要统计一个字符串中每个字母出现的频率。最简单的方法是什么呢?

这是我想到的一个例子……问题是如何让allTheLetters等于这些字母,而不是像这样写allTheLetters = "abcdefg...xyz"。在很多其他编程语言中,我可以直接用letter++来逐个增加字母,但到目前为止,我还没找到在Python中这样做的方法。

def alphCount(text):
  lowerText = text.lower()
  for letter in allTheLetters:  
    print letter + ":", lowertext.count(letter)

10 个回答

9

如果你只是想对一个字符串进行频率统计,可以试试这个:

s = 'hi there'
f = {}

for c in s:
        f[c] = f.get(c, 0) + 1

print f
14

问题是如何让 allTheLetters 等于这些字母 而不需要像这样写 allTheLetters = "abcdefg...xyz"

其实这个功能是字符串模块提供的,你不需要手动一个个输入字母哦;)

import string

allTheLetters = string.ascii_lowercase

def alphCount(text):
  lowerText = text.lower()
  for letter in allTheLetters:  
    print letter + ":", lowertext.count(letter)
72

你问的问题(如何遍历字母表)和你想解决的问题(如何统计字符串中每个字母的出现频率)其实是两个不同的事情。

你可以使用string.lowercase,正如其他人提到的那样:

import string
allTheLetters = string.lowercase

如果你想用你“习惯”的方式,把字母当作数字来处理,可以使用“ord”和“chr”这两个函数。虽然其实没有必要这样做,但这可能更接近你想要理解的内容:

def getAllTheLetters(begin='a', end='z'):
    beginNum = ord(begin)
    endNum = ord(end)
    for number in xrange(beginNum, endNum+1):
        yield chr(number)

你可以通过这段代码打印出True来验证它的正确性:

import string
print ''.join(getAllTheLetters()) == string.lowercase

不过,要解决你真正想解决的问题,你需要使用字典,并在遍历的过程中收集字母:

from collections import defaultdict    
def letterOccurrances(string):
    frequencies = defaultdict(lambda: 0)
    for character in string:
        frequencies[character.lower()] += 1
    return frequencies

使用方法如下:

occs = letterOccurrances("Hello, world!")
print occs['l']
print occs['h']

这将分别打印出'3'和'1'。

注意,这个方法也适用于unicode字符:

# -*- coding: utf-8 -*-
occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!")
print occs[u'l']
print occs[u'ĺ']

如果你尝试用另一种方法处理unicode(逐个字符递增),你可能会等很久,因为unicode字符有数百万个。

要实现你最初的功能(按字母顺序打印每个字母的计数),可以这样做:

def alphCount(text):
    for character, count in sorted(letterOccurrances(text).iteritems()):
        print "%s: %s" % (character, count)

alphCount("hello, world!")

撰写回答