python - 如何在 Python 中遍历字符串?

标签 python

例如,假设我想列出字符串中每个字母的频率。最简单的方法是什么?

这是我正在考虑的一个例子......问题是如何使 allTheLetters 等于所说的字母,而不需要像 allTheLetters = "abcdefg...xyz"这样的东西。在许多其他语言中,我可以只使用 letter++ 并在字母表中递增,但到目前为止,我还没有在 python 中找到这样做的方法。

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

最佳答案

您提出的问题(如何遍历字母表)与您尝试解决的问题(如何计算字符串中字母的频率)不是同一个问题。

您可以使用 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!")

关于python - 如何在 Python 中遍历字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/228730/

相关文章:

python - re.finditer 循环是如何工作的?

python - 根据列的值连续性按行拆分/分组 pandas DataFrame

python 2.7 : log displayed twice when `logging` module is used in two python scripts

python - linux python3错误; "OSError [Errno 98]"或 "The kernel process exited. (0)"

python - aiohttp:装饰器序列链

python - Scrapy MultiCSVItemPipeline 导出一些空项目

python - 使用 boto3 删除 CloudFront 分配

python - 使用 OpenCV 提高用稀释墨水书写的几乎不可见的旧文本的对比度和质量

python - 如何计算 DecisionTreeClassifier 的 0-1 确定性分数?

python - 在 Tkinter 中,我如何从小部件中删除焦点?