将Python字符串写入文件以供Perl脚本读取

2024-10-01 19:30:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python将结果写入一个txt文件,其中每一行的格式都需要是句子标签得分:

<s> This is the sentence </s> 42

其目的是让一个“score\u results”Perl脚本读取句子和分数,其中每一行都被解析为w/@fields = split(/\t/)

$count = 0;
$best = "";
$bestlp = -1000000;

while (<>) {
        s/\s+[\r\n]+$//o;
        @fields = split(/\t/);
        if ($fields[1] > $bestlp) {
                $bestlp = $fields[1];
                $best = $fields[0];
        }

        if ((++$count % 5) == 0) {
                print "$best\n";
                $bestlp = -1000000;
        }
}

我的问题是用Python编写结果语句,带有

with open("results.txt", "wb") as fout:
    for sentence, score in zip(resultsSentences, resultsScores):
        fout.write(sentence + "\t" + str(score) + "\n")

不起作用,因为Python编写的文件中的制表符以新行结束,因此在Perl脚本中不能识别为制表符。“的前几行”结果.txt“看起来像

<s> I have seen it on him , and could write to it </s> 
    42.0
<s> I have seen it on him , and could migrate to it </s> 
    42.0
<s> I have seen it on him , and could climb to it </s> 
    42.0

但是使用Perl脚本运行的示例结果如下

<s> I have seen it on him , and could write to it </s>  -46.8152390767177
<s> I have seen it on him , and could migrate to it </s>    -50.5058224637686
<s> I have seen it on him , and could climb to it </s>  -48.5949070950928

然后“score\u results”Perl脚本与bash调用一起运行 cat results.txt | ./score_results.pl > scores.temp

考虑到我更喜欢使用提供的Perl脚本,如何修改脚本和/或以不同的方式编写结果语句?你知道吗


Tags: andtotxt脚本fieldsonhaveit

热门问题