【问题标题】:how can I transform Perl's $1 special variable to Python? [closed]如何将 Perl 的 $1 特殊变量转换为 Python? [关闭]
【发布时间】:2020-08-17 22:10:27
【问题描述】:

我想将包含 perl 中的哈希的哈希转换为 python。这是它的一段 perl 代码:

our %types = (
  string => {
    db_type     => 'string',
    hint        => 'string',
    pattern     => qr|^(.+)$|,
    format      => q( $1 )
  },
  boolean => {
    db_type     => 'boolean',
    hint        => 'yes|no',
    pattern     => qr|^([yn])|i,
    check       => q( $1 ),
    format      => q( ($1 =~ /^y/) ? 'yes' : 'no' )
  }
)

这是我用 Python 编写的:

types = [
    'string': {
        'db_type': 'string',
        'hint': 'string',
        'pattern': re.compile(r'^(.+)$'),
        # 'format':,
    },
    'boolean': {
        'db_type': 'boolean',
        'hint': 'yes|no',
        'pattern': re.compile(r'^([yn])', re.IGNORECASE),
        #'check': HOW SHOULD I TRANSFORM THIS PART?,
        #'format': HOW SHOULD I TRANSFORM THIS PART?,
    },
]

我不知道应该如何转换格式的值和检查键。 有任何帮助。

【问题讨论】:

  • $1 做了什么
  • 我猜你应该把它做成一个函数,然后返回一个包含这些部分的字典。
  • @jonrsharpe 我没有办法像 Perl 一样就地完成它吗?
  • 您所说的“就地”并不是很清楚。 Python 和 Perl 是根本不同的语言,你不能使用相同的习语。

标签: python perl zoneminder


【解决方案1】:

$1 是存在于计算的正则表达式的第一个括号中的文本部分。

你需要重写整个机制,但是像 .group(1) 代表 $1 以及

"yes" if object.group(1) == "y" else "no" 

($1 =~ /^y/) ? 'yes' : 'no'

应该做的工作。

【讨论】:

    猜你喜欢
    • 2019-09-19
    • 2020-09-19
    • 2021-07-11
    • 1970-01-01
    • 2016-03-31
    • 2015-04-21
    • 1970-01-01
    • 2017-12-25
    • 2015-09-26
    相关资源
    最近更新 更多