3 回答

TA貢獻2037條經(jīng)驗 獲得超6個贊
您可以使用itertools一個小的更改來調(diào)整您的代碼。文件迭代器生成文本行,并且您希望一行中的每個字符。
的chain類用于通過鏈接在一起的多個iterables創(chuàng)建一個新的迭代; 它從一個迭代中產(chǎn)生項目,然后從下一個迭代中產(chǎn)生項目,直到所有原始迭代都用完為止。
由于texto它本身是可迭代的(產(chǎn)生str對象),您可以將這些值鏈接到一個長的“虛擬”中str,從而產(chǎn)生您想要的單個字符。
from itertools import chain
texto = open('teste.txt','r')
ocorrencias = [0] * 26 # You still need 26 slots, even if they are indexed 0 to 25
ord_a = ord("a")
for caracter in chain.from_iterable(texto):
if caracter >= 'a' and caracter <= 'z':
ocorrencias[ord(caracter) - ord_a] += 1

TA貢獻1829條經(jīng)驗 獲得超4個贊
texto = open('teste.txt','r')
ocorrencias = [0] * 26
ord_a = ord("a")
for caracter in texto:
for c in caracter:
if c >= 'a' and c <= 'z':
ocorrencias[ord(c) - ord_a] += 1
print(ocorrencias)
texto.close()

TA貢獻1875條經(jīng)驗 獲得超5個贊
您可以通過在單詞上使用附加循環(huán)來實現(xiàn)它
texto = open('teste.txt','r')
ocorrencias = [0] * 26
ord_a = ord("a")
for words in texto:
for character in words:
if character >= 'a' and character <= 'z':
ocorrencias[ord(character) - ord_a] += 1
添加回答
舉報