【问题标题】:Python sort text file in dictionaryPython对字典中的文本文件进行排序
【发布时间】:2014-06-05 03:34:27
【问题描述】:

我有一个看起来像这样的文本文件:

John Graham 2
Marcus Bishop 0
Bob Hamilton 1
... and like 20 other names.

每个名称出现多次,后面带有不同的数字(分数)。 我需要制作一个列表,只显示每个名字一次,然后加上该名字的总分。我需要使用字典。

这就是我所做的,但它只是从一开始就制作了一个类似于文本文件的列表:

dict = {}

with open('scores.txt', 'r+') as f:
    data = f.readlines()


    for line in data:
        nameScore = line.split()
        print (nameScore)

我不知道下一部分该怎么做。

【问题讨论】:

    标签: python file sorting dictionary


    【解决方案1】:

    这是一个使用defaultdict(int)的选项:

    from collections import defaultdict
    
    result = defaultdict(int)
    with open('scores.txt', 'r') as f:
        for line in f:
            key, value = line.rsplit(' ', 1)
            result[key] += int(value.strip())
    
    print result
    

    如果scores.txt的内容是:

    John Graham 2
    Marcus Bishop 0
    Bob Hamilton 1
    John Graham 3
    Marcus Bishop 10
    

    打印出来:

    defaultdict(<type 'int'>, 
                {'Bob Hamilton': 1, 'John Graham': 5, 'Marcus Bishop': 10})
    

    UPD(格式化输出):

    for key, value in result.iteritems():
        print key, value
    

    【讨论】:

    • 好吧,这行得通,但是“defaultdict(,”必须在那里吗?我想打印一个列表,就像文件从一开始的样子。
    【解决方案2】:

    我的第一关应该是这样的:

    scores = {}  # Not `dict`. Don't reuse builtin names.
    
    with open('scores.txt', 'r') as f:  # Not "r+" unless you want to write later
        for line in f:
            name, score = line.strip().rsplit(' ', 1)
            score = int(score)
            if name in scores:
                scores[name] = scores[name] + score
            else:
                scores[name] = score
    
    print scores.items()
    

    这不完全是我的写作方式,但我想表达得足够明确,以便您可以继续阅读。

    【讨论】:

    • +1 表示不重用内置名称。这是初学者要注意的重要事项!
    • 这也可以,但结果需要是一个列表。我也为此使用 split 吗?
    • dict.items() 方法从该字典返回一个键/值元组列表。我更新了我的答案以反映它。
    【解决方案3】:

    使用字典获取:

    dict = {}
    with open('file.txt', 'r+') as f:
        data = f.readlines()
        for line in data:
            nameScore = line.split()
            l=len(nameScore)
            n=" ".join(nameScore[:l-1])
            dict[n] = dict.get(n,0) + int(nameScore[-1])
    
    print dict
    

    输出:

    {'Bob Hamilton': 1, 'John Graham': 2, 'Marcus Bishop': 0}
    

    【讨论】:

      【解决方案4】:

      我遇到过类似的情况。我修改了Wesley's 代码以适应我的具体情况。我有一个映射文件“sort.txt”,它由不同的 .pdf 文件和数字组成,以根据网站 DOM 操作的输出指示我希望它们的顺序。我想将所有这些单独的 pdf 文件合并到一个 pdf 文件中,但我想保留它们在网站上的顺序。所以我想在导航菜单中根据它们的树位置附加数字。

      1054 spellchecking.pdf
      1055 using-macros-in-the-editor.pdf
      1056 binding-macros-with-keyboard-shortcuts.pdf
      1057 editing-macros.pdf
      1058 etc........
      

      这是我想出的代码:

      import os, sys
      
      # A dict with keys being the old filenames and values being the new filenames
      mapping = {}
      
      # Read through the mapping file line-by-line and populate 'mapping'
      with open('sort.txt') as mapping_file:
          for line in mapping_file:
      
              # Split the line along whitespace
              # Note: this fails if your filenames have whitespace
              new_name, old_name = line.split()
              mapping[old_name] = new_name
      
      
      # List the files in the current directory
      for filename in os.listdir('.'):
          root, extension = os.path.splitext(filename)
      
          #rename, put number first to allow for sorting by name and 
          #then append original filename +e extension
          if filename in mapping:
              print "yay" #to make coding fun
              os.rename(filename, mapping[filename] + filename + extension)
      

      我没有像 _full 这样的后缀,所以我不需要那个代码。除了相同的代码之外,我从来没有真正接触过python,所以这对我来说是一次很好的学习经历。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 2017-10-22
        • 2017-07-12
        • 2023-04-09
        • 2023-03-18
        • 1970-01-01
        • 2011-10-15
        相关资源
        最近更新 更多