簡體   English   中英

如何僅從 python 中的字符串中獲取字母

[英]how to only get the alphabet letter from a string in python

我正在嘗試創建一個程序,該程序從文件中獲取文本並輸出每個字母的頻率。 output 也顯示“.”的頻率。 但我只想 output 的字母頻率。 我正在嘗試使用 isalpha() 但我不確定將它放在哪里。 到目前為止,這是我的代碼:

    d = dict()
    word = str.lower()

    for i in word:
        for j in i:
            if j in d:
                d[j] = d[j] + 1
            else:
                d[j] = 1
    return d

print(count("Once upon a time there lived a princess who was too beautiful and kind to her subjects.The poets and artists were all in praise of her beauty and their works were inspired by her. Once a charming prince from another kingdom came to meet the princess and soon they became friends and slowly they fell in love")) 

我試着把 isalpha() 放在這里:

對於 word.isalpha() 中的 i:

但它只是給我一個錯誤。

我對您所要求的印象是您希望每個字母以及該字母在字符串中出現的次數。

import string

alphabet_string = string.ascii_lowercase
alphabet_list = list(alphabet_string)

letter_count = {}


string = (
    "Once upon a time there lived a princess who was too beautiful and" 
    "kind to her subjects.The poets and artists were all in praise of" 
    "her beauty and their works were inspired"
)

for char in alphabet_list:
    letter_count[char] = 0
for char in string:
    if char in alphabet_list:
        letter_count[char] += 1
print (letter_count)
from string import ascii_lowercase as alphabet 
# or simply declare: alphabet = 'abcdefghijklmnopqrstuvwxyz' 
def letter_frequency(text):    
    frequency = {letter:0 for letter in alphabet}
    for character in text.lower():
        try:
            frequency[character] += 1
        except KeyError:
            pass
    return frequency

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM