Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中迭代字符串?_Python - Fatal编程技术网

如何在Python中迭代字符串?

如何在Python中迭代字符串?,python,Python,举个例子,假设我想在一个字符串中列出字母表中每个字母的频率。最简单的方法是什么 这是我想到的一个例子。。。问题是如何使所有字母与所述字母相等,而不使用类似allTheLetters=“abcdefg…xyz”的内容。在许多其他语言中,我可以只使用字母++并通过字母表递增,但到目前为止,我还没有在python中找到这样做的方法 def alphCount(text): lowerText = text.lower() for letter in allTheLetters: p

举个例子,假设我想在一个字符串中列出字母表中每个字母的频率。最简单的方法是什么

这是我想到的一个例子。。。问题是如何使所有字母与所述字母相等,而不使用类似allTheLetters=“abcdefg…xyz”的内容。在许多其他语言中,我可以只使用字母++并通过字母表递增,但到目前为止,我还没有在python中找到这样做的方法

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

for letter in range(ord('a'), ord('z') + 1):
  print chr(letter) + ":", lowertext.count(chr(letter))
问题是如何使 与上述字母相等的所有字母 没有像所有字母一样的东西= “abcdefg…xyz”

这实际上是由字符串模块提供的,您不必自己手动键入;)

你的意思是使用:

import string
string.ascii_lowercase
那么

所有小写字母均已计算,缺少的计数器将为零值

使用发电机:

counters = 
    dict( (letter,lowertext.count(letter)) for letter in string.ascii_lowercase )

如果只想对字符串进行频率计数,请尝试以下操作:

s = 'hi there'
f = {}

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

print f
主要问题是“反复阅读字母表”:

如何在不计算非字母字符的情况下有效地获取字母频率:

import string

sample = "Hello there, this is a test!"
letter_freq = dict((c,0) for c in string.lowercase)

for c in [c for c in sample.lower() if c.isalpha()]:
    letter_freq[c] += 1

print letter_freq
您所问的问题(如何遍历字母表)与您试图解决的问题(如何计算字符串中字母的频率)不同

正如其他海报所建议的,您可以使用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!")
对于计算对象,显而易见的解决方案是

我就是这么做的:

import string
for x in list(string.lowercase):
    print x

这个怎么样,使用字母、数字和标点符号(都可以用来组成Django键):

示例结果:酷:V!D+P和S*hzbO{a0_6]2!{4|oibVabq0:

只需使用:

import string
string.lowercase  
string.uppercase


我认为count()中的“letter”应该是“chr(letter)”,因为您已经修复了它(并且没有因为一个错误而关闭我的帐户,导致只检查到“y”:-),我删除了我的答案,并对你的答案投了更高的票。@Adam:我暂时否决了它,以将其从最上面的位置删除,并提升Matthew的答案。这也不是很好的Python代码。@John:噢,市场操纵。SEC监控这些论坛吗?:-)这是一个非常愚蠢的解决方案,因为它只在给定的字符串上迭代一次,因此是O(n)与使用嵌套迭代相反。如果使用f=defaultdict(int)和简单的f[c]+=1作为get成员O(1),事件会更好?如果是O(n),那么整个事情就是O(n^2)。@Pax Diablo:映射是散列的。字典get是O(1)。这个解决方案很慢,因为它有嵌套迭代(lowertext.count()迭代字符串以查找计数)但是,特定问题已得到回答。其他问题是原始问题。或者,您可以通过对以下列表进行迭代来获取所有小写字母:allTheLetters=[chr(i+97)表示范围(26)内的i]你真的应该使用string.ascii_小写,而不是编写你自己的GetAlltheletter。而且,对于函数来说,这是一个非常不和谐的名字!你的letterOccurrances()函数还将计算空格和标点符号,可能不是有意的。实际上Unicode字符的数量仍在一百万以下。还有一些字符是非字母的,所以在打印频率时要排除这些字符。“string.ascii_小写”--我希望有一个unicode_小写字母来处理西里尔文、希腊文等。我希望它知道如何根据当前的语言环境而不是collections.defaultdict(lambda:0),使用collections.defaultdict(int)将土耳其语I的大小写正确将做同样的事情,而且更清晰。更简单的是,您可以用:
c=Counter(text.lower())
def alphCount(text):
    for character, count in sorted(letterOccurrances(text).iteritems()):
        print "%s: %s" % (character, count)

alphCount("hello, world!")
from collections import Counter
import string

c = Counter()
for letter in text.lower():
    c[letter] += 1

for letter in string.lowercase:
    print("%s: %d" % (letter, c[letter]))
import string
for x in list(string.lowercase):
    print x
import random
import string

chars = string.letters + string.digits + string.punctuation
chars_len = len(chars)
n = 40

print(''.join([chars[random.randint(0, chars_len)] for i in range(n)]))
import string
string.lowercase  
string.uppercase
string.letters[:26]  
string.letters[26:]