【问题标题】:print truth table in to odt file将真值表打印到 odt 文件
【发布时间】:2018-03-08 08:06:03
【问题描述】:

我想将真值表打印到 adt 文件中的表中,我有一个程序,但我不知道如何获取要打印到 odt 文件的值或值,这个程序只是在屏幕上打印结果!

sub truth_table {
    my $s = shift;
    #print "$s\n";
    my  @vars;
    for ($s =~ /([a-zA-Z_]\w*)/g) {
        push @vars, $_ ;

    }
    #print "$s\n";
    #print "$_\n";
    #print Dumper \@vars;
    #print "\n", join("\t", @vars, $s), "\n", '-' x 40, "\n";
    #print Dumper \@vars;
    @vars = map("\$$_", @vars);
    $s =~ s/([a-zA-Z_]\w*)/\$$1/g;
    $s = "print(".join(',"\t",', map("($_?'1':'0')", @vars, $s)).",\"\\n\")";
    $s = "for my $_ (0, 1) { $s }" for (reverse @vars);
    eval $s;
}
truth_table 'A ^ A_1';

【问题讨论】:

  • this 应该能帮到你
  • 我知道那个链接,但问题是如何将 A 和 A_1 的值以及结果带到 @array 或 %hash 以使用它们

标签: perl openoffice-writer odt


【解决方案1】:

Capture::Tiny得到eval的结果,然后根据https://stackoverflow.com/a/4226073/5100564将字符串拆分成二维数组。

use Capture::Tiny 'capture_stdout';

sub truth_table {
    #...the rest of your code here...
    my $stdout = capture_stdout {
        eval $s;
    };
    return $stdout;
}
$truth_string = truth_table 'A ^ A_1';
my @truth_array;
foreach my $line (split "\n", $truth_string) {
    push @truth_array, [split ' ', $line];
}
foreach my $line (@truth_array) {
    foreach my $val (@$line) {
        print $val;
    }
    print "\n";
}

为此,我基于What's the easiest way to install a missing Perl module?执行了以下命令

cpan
install Capture::Tiny

但是,我会在 LibreOffice 中使用 Python 宏来解决这个问题。 APSO 方便输入和运行这段代码。

import uno
from itertools import product

def truth_table():
    NUM_VARS = 2  # A and B
    columns = NUM_VARS + 1
    rows = pow(2, NUM_VARS) + 1
    oDoc = XSCRIPTCONTEXT.getDocument()
    oText = oDoc.getText()
    oCursor = oText.createTextCursorByRange(oText.getStart())
    oTable = oDoc.createInstance("com.sun.star.text.TextTable")
    oTable.initialize(rows, columns)
    oText.insertTextContent(oCursor, oTable, False)
    for column, heading in enumerate(("A", "B", "A ^ B")):
        oTable.getCellByPosition(column, 0).setString(heading)
    row = 1  # the second row
    for p in product((0, 1), repeat=NUM_VARS):
        result = truth_function(*p)
        for column in range(NUM_VARS):
            oTable.getCellByPosition(column, row).setString(p[column])
        oTable.getCellByPosition(column + 1, row).setString(result)
        row += 1

def truth_function(x, y):
    return pow(x, y);

g_exportedScripts = truth_table,

这样使用product是基于Creating a truth table for any expression in Python

更多关于 Python-UNO 的文档可以在https://wiki.openoffice.org/wiki/Python找到。

【讨论】:

  • $s = "print(".join(',"\t", ', map("($_?'1':'0')", @vars, $s) ).",\"\\n\")";如何在不打印的情况下加入,每次我制作真值表时它都会再次打印在屏幕上,但我不需要屏幕上的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 2011-03-03
  • 2012-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多