【问题标题】:Count and show how many times a line is duplicated in a file计算并显示文件中一行重复的次数
【发布时间】:2019-01-11 16:16:20
【问题描述】:

我在 bash 中看到过解决方案(即问题 6712437),但我没有找到任何适用于 python 的解决方案。

我正在尝试搜索文件,找到重复的行并输出重复的次数。

输入

foo
bar
foo
foo
bar
foobar

输出

foo     3
bar     2
foobar  1

【问题讨论】:

  • 到目前为止你尝试过什么?您是否从collections 调查过Counter
  • 您知道如何以字符串列表的形式打开和读取文件吗?你知道如何在循环中使用字典吗?
  • @JordanSinger 我以前使用 counter 和 re.findall 来处理各种事情,但主要是搜索特定的事情/正则表达式模式。我想不出一种方法来将它应用于搜索重复项。我不是 CS,所以边搜索边学习

标签: python search duplicates find


【解决方案1】:

这是我的解决方案:

lines = [] #List of line items
itemcounts = {}  #dictionary of items with counts
with open('myfile.txt') as f: 
    for item in f:
        lines.append(item)
for i in lines:
    c = lines.count(i) 
    itemcounts.update({i:c})
#print items and counts
for i in itemcounts: 
    print i, itemcounts[i]

【讨论】:

    【解决方案2】:

    最简单的解决方案是使用collections.Counter。但是,如果您不想包含额外的库,那么

    d={}
    with open('test.txt') as f:
        for i in f:
            d[i]=d.get(i,0)+1
    
        sorted_items = sorted(d.items(),key=lambda (k,v): (v,k),reverse=True)
        #iterate to save or play around with tuple values
    

    【讨论】:

      【解决方案3】:

      collections.Counter 似乎是个不错的选择。

      要计算文件中每一行的出现次数,您可以尝试:

      import collections
      
      with open('myfile.txt') as f:
          c = collections.Counter(f.readlines())
      

      然后,为了获得良好的输出(就像您在对此答案的评论中要求的那样),您可以使用:

      # sorted by value (number of occurences, but descending order)
      for k, v in c.most_common():
          print(k, v)
      
      # sorted by value (number of occurences, ascending order)
      for k, v in sorted(c.items(), key=lambda x: x[1]):
          print(k, v)
      
      # sorted by key (line of the file)
      for k, v in sorted(c.items(), key=lambda x: x[0]):
          print(k, v)
      

      【讨论】:

      • 谢谢,这工作..我添加到脚本后处理和创建新行等,所以它更容易阅读.. j/w 是否有另一种方法让它最初用新线?
      • 我不明白你需要什么。您能否将您的脚本添加到您的问题中(或提出一个新问题)并更详细地解释它?
      • 对不起,让我解释得更好.. 使用collections.counter,输出就像Counter ({'FOO\n': 17097, 'BAR\n': 16512, 'FOOBAR\n': 16154,.......,正如预期的那样,我使它可用的方法是转换为字符串,写入文档,然后插入换行,替换字符等来格式化它。我想知道是否有“更好”的方式
      • @physlexic 我编辑了我的答案以添加很好地格式化结果的方法
      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      • 1970-01-01
      • 2014-08-04
      相关资源
      最近更新 更多