【问题标题】:Perl or Python: Count total number of different Mac addresses in a file [closed]Perl或Python:计算文件中不同Mac地址的总数[关闭]
【发布时间】:2013-11-15 16:55:35
【问题描述】:

我有一个包含数千个 mac 地址的大文件 (~10-100MB),每个 mac 地址可能在文件中出现多次。 我想编写一个返回唯一 MAC 地址总数的 Perl 脚本(或 Python 脚本)。例如,如果我的文件包含

"hostmac":"112233445566"
log here
"hostmac":"23AA23AA23AA"
log here
"hostmac":"23AA23AA23AA"
log here
"hostmac":"112233445566"
log here
"hostmac":"77AABB8899CC"
log here
"hostmac":"112233445566"
log here
"hostmac":"112233445566"
log here
"hostmac":"EEFF00112233"
log here

我希望我的 Perl/Python 脚本返回 4,因为我有 4 个唯一的 mac 地址。

【问题讨论】:

  • 到目前为止你有什么收获?
  • 每一行的格式是否相同?

标签: python perl unique


【解决方案1】:

如果格式和你描述的一样:

$ egrep hostmac filename.txt | sort -u | wc -l

【讨论】:

  • 感谢 Rob,非常感谢您的帮助。这正是我需要的。 Thaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaanks ;-)
【解决方案2】:
perl -nE '$s{$1} = 1 if /hostmac":"(.+?)"/ END{ say scalar keys %s }' file

对于 perl 5.8 及更早版本:

perl -ne '$s{$1} = 1 if /hostmac":"(.+?)"/ END{ print scalar keys %s }' file

【讨论】:

  • Perl 既性感又肮脏。
  • @admdrew 性感,是的,只有在混淆时才肮脏:)
  • 有时 perl 会让人感到困惑,即使是好的代码 :D
  • 非常感谢。我收到此错误,请您帮帮我: $ perl -nE '$s{$1} = 1 if /hostmac":"(.+?)"/ END{ say scalar keys %s }' test.txt Unrecognized开关:-E(-h 将显示有效选项)。 $ perl -n '$s{$1} = 1 if /hostmac":"(.+?)"/ END{ say scalar keys %s }' test.txt Can't open perl script "$s{$1} = 1 if /hostmac":"(.+?)"/END{ say scalar keys %s }": No such file or directory
  • @user2996850 检查更新;您使用的是过时的 perl 版本
【解决方案3】:

假设每一行都有上面列出的格式,Python 将是:

len(set([line.split(':')[1] for line in open(path)]))

【讨论】:

    【解决方案4】:

    使用可读 Python 的 Python 答案

    def count_unique(filename):
        mac_addr = set()
        with open(filename) as f:
            for line in f:
                if 'hostmac' in line:
                    mac_addr.add(line.split('"')[-2])
        return len(mac_addr)
    
    if __name__ == '__main__':
        import sys
        print count_unique(sys.argv[1])
    

    使用更简洁格式的 Python 答案

    import sys
    with open(sys.argv[1]) as f:
        print len(set(line.split('"')[-2] for line in f if 'hostmac' in line))
    

    【讨论】:

      【解决方案5】:

      Python 解决方案:

      with open ('data.txt') as f:
          print len(set(line for line in f if line.startswith('"hostmac":')))
      

      这实际上可以是单行的,print 可以与with ... 在同一行:-) 很容易看出使用grepuniqwc 的解决方案是不过最短。在几秒钟内学会 Unix 工具来做这些事情是件好事。

      【讨论】:

        猜你喜欢
        • 2021-01-20
        • 2016-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-12
        • 1970-01-01
        相关资源
        最近更新 更多