【问题标题】:Each loop of an if statement, save to a different variableif 语句的每个循环,保存到不同的变量
【发布时间】:2015-10-10 16:58:24
【问题描述】:

我正在尝试获取文档中字母的频率,然后将它们拆分为单独的变量,以便将它们转换为百分比。我遇到的问题是变量 var1 每次 if 语句循环时都会被重写......我不确定如何将 26 个字符的频率中的每一个写入单独的变量,这样我就可以将它们转换为百分比并单独使用每个百分比。

这是我的代码,var1 最终打印为文件中最后一个或最不常见的字母:

def freq():
    info = input("File Name")
    filehandle = open(info, "r")
    data = filehandle.read().upper()
    char_counter = collections.Counter(data)
    for char, count in char_counter.most_common():
        if char in string.ascii_uppercase:
            s = (str(count))
            my_tokens = s.split("|")
            print(my_tokens)
            global var1
            var1 = my_tokens[0]

freq()
print(var1)

任何帮助将不胜感激,因为我有点不知所措。谢谢。

【问题讨论】:

    标签: python variables count split char


    【解决方案1】:

    将每个字符频率存储到一个哈希(映射)中,其中键是字符本身,值是整数。遇到的每个字符递增整数值

    【讨论】:

    【解决方案2】:

    你想使用dict

    def freq():
        info = input("File Name")
        filehandle = open(info, "r")
        data = filehandle.read().upper()
        char_counter = collections.Counter(data)
        result = {}
        for char, count in char_counter.most_common():
            if char in string.ascii_uppercase:
                s = (str(count))
                my_tokens = s.split("|")
                print(my_tokens)
                result[char] = my_tokens[0]
    
    result = freq()
    print(result)
    

    【讨论】:

      【解决方案3】:

      您可以使用dictionary,其中您的 char 是键,值是出现次数,就像这样:

      import collections
      
      def freq():
          var1 = dict()
          info = input("File Name")
          filehandle = open(info, "r")
          data = filehandle.read().upper()
          char_counter = collections.Counter(data)
          for char, count in char_counter.most_common():
              if char in data.upper():
                  s = (str(count))
                  my_tokens = s.split("|")
                  print(my_tokens)
                  var1[char] = my_tokens[0]
          return var1
      
      var1 = freq()
      print(var1)
      

      你可以在这里阅读更多关于字典的使用http://www.tutorialspoint.com/python/python_dictionary.htm

      【讨论】:

        猜你喜欢
        • 2019-05-24
        • 2020-08-20
        • 1970-01-01
        • 1970-01-01
        • 2018-07-02
        • 2014-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多