使用字典,按频率计数字母

时间:2019-11-26 02:39:16

标签: python dictionary count frequency letter

我想知道是否有人可以帮助我。

如何获取此代码,以仅将文本文件中字母的频率记录到字典中(不计算空格,行,数字等)?

另外,如何将每个字母除以总字母,以报告文件中每个字母的频率百分比?

这是我目前拥有的:

def linguisticCalc():
    """
    Asks user to input a VALID filename. File must be a text file. IF valid, returns the frequency of ONLY letters in file.

    """
    filename = input("Please type your VALID filename")
    if os.path.exists(filename) == True:
        with open(filename, 'r') as f:
            f_content = f.read()
            freq = {}
            for i in f_content:
                if i in freq:
                    freq[i] += 1
                else:
                    freq[i] = 1
        print(str(freq))

    else:
        print("This filename is NOT valid. Use the getValidFilename function to test inputs.")

2 个答案:

答案 0 :(得分:0)

可以帮助您确定所讨论字符是否为字母的东西是

$(function() {
  function makeModal(cnt, t) {
    var dlg = $("<div>", {
      title: t
    }).html(cnt);
    dlg.dialog({
      classes: {
        "ui-dialog": "clear",
        "ui-dialog-titlebar": "pale",
        "ui-dialog-content": "clear",
        "ui-dialog-buttonpane": "no-show",
        "ui-dialog-buttonset": "no-show"
      },
      resizable: false,
      modal: true,
      width: 550,
      height: 722,
      show: {
        effect: "fade",
        duration: 300
      },
      close: function(e, ui) {
        $(this).dialog("destroy");
      }
    });
  }

  $(".thumb").click(function(e) {
    e.preventDefault();
    var i = $(this).find("img");
    makeModal(i.prop("outerHTML"), i.attr("alt"));
  })
});

答案 1 :(得分:0)

签出collections.Counter()

您可以使用它来计数字符串中的每个字母:

Counter('Articles containing potentially dated statements from 2011')

它给出以下输出,这对于计数字符串中的字符很有用:

  

计数器({'A':1,            'r':2            't':8            '我':4,            'c':2            'l':3,            'e':5            's':3,            '':6,            'o':3,            'n':5            'a':4            'g':1            'p':1,            'y':1            'd':2            'm':2            'f':1            '2':1            '0':1            '1':2})