【问题标题】:How to transform a string parenthesis to a parent-child represantion如何将字符串括号转换为父子表示
【发布时间】:2014-01-14 19:23:38
【问题描述】:

我正在尝试以这种格式的单个字符串可视化一个公式:

AND(operator1(operator2(x,a),operator3(y,b)),operator4(t))

一个运算符中的参数数量没有限制。

目前我正在尝试在 perl 中解决它。我想最简单的方法是将其转换为父子表示,然后以这样的可折叠方式呈现它会很容易:

[-]AND(
  [-]operator1(
    [-]operator2(
      x
      a
    )
    [+]operator3(...)
  )
  [-]operator4(
    t
  )
)

我怀疑我是第一个解决这个问题的人,但我在网上找不到任何这样的例子。谢谢!

【问题讨论】:

  • 定义“可视化”。你想打印出运算符和操作数的树吗?还是别的什么?
  • 请编辑问题以通过示例 o/p 增加问题的可理解性
  • 问题不清楚,但很可能您需要创建语法解析器。您可以使用递归正则表达式匹配来做到这一点。也请查看Regexp::Grammars
  • 我编辑了一下并添加了一个示例。但我最希望将其转换为哈希,然后再决定如何在页面上显示它
  • 所以您希望在某种交互式视图中呈现此字符串?如果是这样,那会稍微改变您的问题范围。

标签: perl data-visualization parentheses


【解决方案1】:

几个月前我做了类似的事情,并认为这可能符合您正在寻找的内容......

c:\Perl>perl StackOverflow.pl
SomeValue
AND
-operator1
--operator2
---x
---a
--operator3
---y
---b
-operator4
--t

c:\Perl>

如果是这样,这是代码(如下)。这有点乱,但应该足以让你开始。

#!c:/perl/bin/perl.exe

my $SourceString="SomeValue AND (operator1(operator2(x,a),operator3(y,b)),operator4(t))";
my $NodeIndex=0;
my $IndexString="-";
print ProcessString($SourceString, $NodeIndex);
exit;

#----- subs go here -----
sub ProcessString {
    my $TargetString=shift||return undef;
    my $NodeIndex=shift;
    my $ReturnString="";

    #are we starting with a paren or comma?
    if($TargetString=~m/^([\(\)\, ])/) {
        #yep, delete the char and pass it through again for further processing
        if($1 eq " ") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), $NodeIndex);}
        elsif($1 eq ",") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), $NodeIndex);}
        elsif($1 eq "(") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), ++$NodeIndex);}
        elsif($1 eq ")") {$ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)+1), --$NodeIndex);}
    } else {
        #nope, must be a keyword or the end
        if($TargetString=~m/([\(\)\, ])/) {
            my $KeywordString=substr($TargetString, 0, index($TargetString, $1));
            $ReturnString.=$IndexString x $NodeIndex;
            $ReturnString.=$KeywordString."\n";
            $ReturnString.=ProcessString(substr($TargetString, index($TargetString, $1)), $NodeIndex);
        } else {
            #we should never be here
        } #end keyword check if
    } #end if

    #send the string back
    return $ReturnString;
} #end sub

__END__

【讨论】:

    猜你喜欢
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 2019-09-29
    • 2010-09-07
    • 2019-02-01
    • 2019-05-20
    • 1970-01-01
    相关资源
    最近更新 更多