“ord() 需要一个字符,但是长度为 15 的字符串......”

我需要知道每个字母在一个句子中出现多少次。但是,它给出了一个错误“ord () 需要一个字符,但字符串长度为 15”(15 和我当前文件中包含的字母数量)


texto = open('teste.txt','r')

ocorrencias = [0] * 25 


ord_a = ord("a")


for caracter in texto:

    if caracter >= 'a' and caracter <= 'z':

        ocorrencias[ord(caracter) - ord_a] += 1


BIG阳
浏览 183回答 3
3回答

阿晨1998

您可以使用itertools一个小的更改来调整您的代码。文件迭代器生成文本行,并且您希望一行中的每个字符。的chain类用于通过链接在一起的多个iterables创建一个新的迭代; 它从一个迭代中产生项目,然后从下一个迭代中产生项目,直到所有原始迭代都用完为止。由于texto它本身是可迭代的(产生str对象),您可以将这些值链接到一个长的“虚拟”中str,从而产生您想要的单个字符。from itertools import chaintexto = open('teste.txt','r')ocorrencias = [0] * 26&nbsp; # You still need 26 slots, even if they are indexed 0 to 25ord_a = ord("a")for caracter in chain.from_iterable(texto):&nbsp; &nbsp; if caracter >= 'a' and caracter <= 'z':&nbsp; &nbsp; &nbsp; &nbsp; ocorrencias[ord(caracter) - ord_a] += 1

浮云间

texto = open('teste.txt','r')ocorrencias = [0] * 26ord_a = ord("a")for caracter in texto:&nbsp; &nbsp; for c in caracter:&nbsp; &nbsp; &nbsp; &nbsp; if c >= 'a' and c <= 'z':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ocorrencias[ord(c) - ord_a] += 1print(ocorrencias)texto.close()

慕田峪4524236

您可以通过在单词上使用附加循环来实现它texto = open('teste.txt','r')ocorrencias = [0] * 26&nbsp;ord_a = ord("a")for words in texto:&nbsp; &nbsp; for character in words:&nbsp; &nbsp; &nbsp; &nbsp; if character >= 'a' and character <= 'z':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ocorrencias[ord(character) - ord_a] += 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python