举个例子,假设我想在字符串中列出字母表中每个字母的频率.最简单的方法是什么?
这是我正在考虑的一个例子......问题是如何使allTheLetters等于所有字母,而不是像allTheLetters ="abcdefg ... xyz".在许多其他语言中,我可以用字母++来增加字母表中的方式,但到目前为止我还没有遇到过在python中这样做的方法.
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
Run Code Online (Sandbox Code Playgroud)
Gly*_*yph 72
你问的问题(如何迭代字母表)与你试图解决的问题(如何计算字符串中字母的频率)不是同一个问题.
你可以使用string.lowercase,正如其他海报所建议的那样:
import string
allTheLetters = string.lowercase
Run Code Online (Sandbox Code Playgroud)
要按照"习惯"的方式做事,将字母视为数字,可以使用"ord"和"chr"函数.绝对没有理由做到这一点,但也许它更接近你实际想要弄清楚的东西:
def getAllTheLetters(begin='a', end='z'):
beginNum = ord(begin)
endNum = ord(end)
for number in xrange(beginNum, endNum+1):
yield chr(number)
Run Code Online (Sandbox Code Playgroud)
你可以告诉它做对了,因为这段代码打印出来True:
import string
print ''.join(getAllTheLetters()) == string.lowercase
Run Code Online (Sandbox Code Playgroud)
但是,要解决您实际尝试解决的问题,您需要使用字典并随时收集字母:
from collections import defaultdict
def letterOccurrances(string):
frequencies = defaultdict(lambda: 0)
for character in string:
frequencies[character.lower()] += 1
return frequencies
Run Code Online (Sandbox Code Playgroud)
使用如下:
occs = letterOccurrances("Hello, world!")
print occs['l']
print occs['h']
Run Code Online (Sandbox Code Playgroud)
这将分别打印'3'和'1'.
请注意,这也适用于unicode:
# -*- coding: utf-8 -*-
occs = letterOccurrances(u"hé??ó, ?ó??d!")
print occs[u'l']
print occs[u'?']
Run Code Online (Sandbox Code Playgroud)
如果你在unicode上尝试另一种方法(递增每个字符),你会等待很长时间; 有数百万的unicode字符.
要实现原始功能(按字母顺序打印每个字母的计数),请执行以下操作:
def alphCount(text):
for character, count in sorted(letterOccurrances(text).iteritems()):
print "%s: %s" % (character, count)
alphCount("hello, world!")
Run Code Online (Sandbox Code Playgroud)
Mat*_*vor 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)
Run Code Online (Sandbox Code Playgroud)
如果您只想进行字符串的频率计数,请尝试以下方法:
s = 'hi there'
f = {}
for c in s:
f[c] = f.get(c, 0) + 1
print f
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67183 次 |
| 最近记录: |