【问题标题】:Letter frequency for loop in PythonPython 中循环的字母频率
【发布时间】:2022-11-22 12:09:09
【问题描述】:

嘿,有人能帮我吗 我应该在这里使用 for 循环和 if 语句为这个字符串中使用的每个字母计算一个数字。

quote=“当我看到她游过海洋时,我敬畏地看着”

给出的伪代码是这样的:

for every letter in the alphabet list:
    Create a variable to store the frequency of each letter in the string and assign it an initial value of zero
    for every letter in the given string:
        if the letter in the string is the same as the letter in the alphabet list
            increase the value of the frequency variable by one.
    if the value of the frequency variable does not equal zero:
        print the letter in the alphabet list followed by a colon and the value of the frequency variable

这是我到目前为止所得到的,但我无法终生弄清楚。

quote =  "I watched in awe as I saw her swim across the ocean."

xquote= quote.lower()
print(xquote)

alphabet= ["a", "b", "c", "d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for i in alphabet:
  c_alphabet= {"a": 0, "b":0, "c":0, "d":0,"e":0,"f":0,"g":0,"h":0,"i":0,"j":0,"k":0,"l":0,"m":0,"n":0,"o":0,"p":0,"q":0,"r":0,"s":0,"t":0,"u":0,"v":0,"w":0,"x":0,"y":0,"z":0}
  for i in xquote:
    if i == alphabet:
      c_alphabet[i]+=1
print(c_alphabet)

我没有收到错误消息,但我似乎无法获得字符串中单个字母的总数。

我希望它输出这样的内容 c alphabet = {"a": 3, "b":1, "c": 2...)

【问题讨论】:

    标签: python


    【解决方案1】:

    有更多雄辩的方法可以做到这一点,但使用你的算法,问题是你混淆了变量。您正在比较 ialphabet,隐藏变量 i,并在每个顶级循环中重新定义 c_alphabet。在此处查看更改:

    quote = "I watched in awe as I saw her swim across the ocean."
    
    xquote = quote.lower()
    print(xquote)
    
    alphabet = [
        "a",
        "b",
        "c",
        "d",
        "e",
        "f",
        "g",
        "h",
        "i",
        "j",
        "k",
        "l",
        "m",
        "n",
        "o",
        "p",
        "q",
        "r",
        "s",
        "t",
        "u",
        "v",
        "w",
        "x",
        "y",
        "z",
    ]
    
    c_alphabet = { # moved out of loop
        "a": 0,
        "b": 0,
        "c": 0,
        "d": 0,
        "e": 0,
        "f": 0,
        "g": 0,
        "h": 0,
        "i": 0,
        "j": 0,
        "k": 0,
        "l": 0,
        "m": 0,
        "n": 0,
        "o": 0,
        "p": 0,
        "q": 0,
        "r": 0,
        "s": 0,
        "t": 0,
        "u": 0,
        "v": 0,
        "w": 0,
        "x": 0,
        "y": 0,
        "z": 0,
    }
    
    for i in alphabet:
        for j in xquote: # changed variable name
            if i == j:   # changed comparison
                c_alphabet[i] += 1
    print(c_alphabet)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多