【问题标题】:Convert Perl syntax to Python [duplicate]将 Perl 语法转换为 Python [重复]
【发布时间】:2017-09-06 15:37:15
【问题描述】:

我有一个文件,其中的行由空格分隔。

我用 Perl 编写了下面的程序,它可以工作。 现在我必须用 Python 重写它,这不是我的语言,但我或多或少地解决了它。

我目前在 Perl 中遇到了这个表达式,我无法将其转换为 Python。

$hash{$prefix}++;

我找到了一些解决方案,但我没有足够的 Python 经验来解决这个问题。与 Perl 相比,所有解决方案在我看来都比较复杂。

这些 Stack Overflow 问题似乎是相关的。

Python variables as keys to dict

Python: How to pass key to a dictionary from the variable of a function?

Perl

#!perl -w

use strict;
use warnings FATAL => 'all';

our $line = "";
our @line = "";
our $prefix = "";
our %hash;
our $key;

while ( $line = <STDIN> ) {
  # NAMESPACE                NAME                                         READY     STATUS             RESTARTS   AGE       IP               NODE
  next if $line =~ /^NAMESPACE/;

  #aleks-event-test         redis-1-m06k0                                1/1       Running            0          1d        172.26.0.138     The_Server_name
  @line = split ' ', $line;
  $line[1] =~ /(.*)-\d+-\w+$/ ;
  $prefix = $1;
  #print "$prefix $line[7]\n";
  print "$prefix $line[7]\n";
  $hash{$prefix}++;
}

foreach $key ( keys %hash ) {
  if ( $hash{$key} / 2 ){
    print "$key : $hash{$key} mod 2 \n"
  }
  else {
    print "$key : $hash{$key} not mod 2 \n"
  }
}

Python

#!python

import sys
import re

myhash = {}

for line in sys.stdin:
    """
    Diese Projekte werden ignoriert
    """
    if re.match('^NAMESPACE|logging|default',line):
        continue
    linesplited = line.split()
    prefix = re.split('(.*)(-\d+)?-\w+$',linesplited[1])
    #print  linesplited[1]
    print prefix[1]
    myhash[prefix[1]] += 1

【问题讨论】:

  • 您的条件 if ( $hash{$key} / 2 ) 很奇怪。仅当 $hash{$key} 为零时,这将是 false。你的意思是if ( $hash{$key} % 2 ) 吗?
  • 好收获。这是 '%' 我刚刚测试了另一个想法 :-)

标签: python perl migration


【解决方案1】:

你的问题是使用这一行:

myhash = {}
# ... code ...
myhash[prefix[1]] += 1

您可能会收到KeyError。这是因为您从一个空字典(或哈希)开始,如果您尝试引用一个尚不存在的键,Python 将引发异常。

让您的脚本工作的简单解决方案是使用defaultdict,它会自动初始化您尝试访问的任何键值对。

#!python

import sys
import re
from collections import defaultdict

# Since you're keeping counts, we'll initialize this so that the values
# of the dictionary are `int` and will default to 0
myhash = defaultdict(int)

for line in sys.stdin:
    """
    Diese Projekte werden ignoriert
    """
    if re.match('^NAMESPACE|logging|default',line):
        continue
    linesplited = line.split()
    prefix = re.split('(.*)(-\d+)?-\w+$',linesplited[1])
    #print  linesplited[1]
    print prefix[1]
    myhash[prefix[1]] += 1

【讨论】:

  • 将默认值指定为defaultdict(lambda: 0) 可能更明显,而不是defaultdict(int),但这只是个人喜好问题。
  • 感谢 birryree 和 amon 的快速答复。抱歉重复了,有时挑战是正确的问题
猜你喜欢
  • 2017-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 2016-05-28
  • 1970-01-01
  • 2014-07-07
  • 2020-04-20
相关资源
最近更新 更多