将Perl语法转换为Python

Ale*_*dar -1 python migration perl

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

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

我目前在Perl中使用这个表达式很困难,我无法将其转换为Python.

$hash{$prefix}++;
Run Code Online (Sandbox Code Playgroud)

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

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

Python变量作为dict的键

Python:如何从函数变量中将键传递给字典?

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"
  }
}
Run Code Online (Sandbox Code Playgroud)

蟒蛇

#!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
Run Code Online (Sandbox Code Playgroud)

wkl*_*wkl 5

你的问题是使用这一行:

myhash = {}
# ... code ...
myhash[prefix[1]] += 1
Run Code Online (Sandbox Code Playgroud)

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

让脚本工作的简单解决方案是使用a 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
Run Code Online (Sandbox Code Playgroud)