gpt4 book ai didi

perl - 如何在 Perl 中从终端获取输入

转载 作者:行者123 更新时间:2023-12-05 00:52:52 26 4
gpt4 key购买 nike

我正在创建一个简单的聊天机器人程序,如 ELIZA .
我正在从终端接受问题并通过对话框发送回复,但我的程序只接受第一个输入并重复。
例如,当我运行我的脚本时,输出可能是这样的:

[Eliza]: Hi, I'm a psychotherapist. What is your name?
user Input: hello my name is adam.
[Eliza]: hello adam, how are you?
[Eliza]: your name is adam
[Eliza]: your name is adam
[Eliza]: your name is adam
[Eliza]: your name is adam
[Eliza]: your name is adam
它无休止地重复。
我不知道我哪里做错了。如何让我的程序从键盘读取下一行?
sub hello {
print "[Eliza]: Hi, I'm a psychotherapist. What is your name? \n";
}


sub getPatientName {
my ($reply) = @_;

my @responses = ( "my name is", "i'm", "i am", "my name's" );

foreach my $response ( @responses ) {

if ( lc($reply) =~ /$response/ ) {
return "$'";
}
}

return lc($reply);
}

sub makeQuestion {
my ($patient) = @_;

my %reflections = (
"am" => "are",
"was" => "were",
"i" => "you",
"i'd" => "you would",
"i've" => "you have",
"i'll" => "you will",
"my" => "your",
"are" => "am",
"you've"=> "I have",
"you'll"=> "I will",
"your" => "my",
"yours" => "mine",
"you" => "me",
"me" => "you"
);

if ( $count == 0 ) {
$patientName = getPatientName($patient);
$count += 1;
print "Hello $patientName , How are you? \n";
}

my @toBes = keys %reflections;

foreach my $toBe (@toBes) {

if ($patient =~/$toBe/) {
$patient=~ s/$toBe/$reflections{$toBe}/i;
print "$patient? \n";
}
}
}

sub eliza {

hello();

my $answer = <STDIN>;

while ($answer) {
chomp $answer;
#remove . ! ;
$answer =~ s/[.!,;]/ /;
makeQuestion($answer);
}
}

eliza();

最佳答案

您的 while循环从不读取输入。 $answer得到 STDIN在循环之前,大概有一个字符串,在 while 中计算为真健康)状况。循环中的正则表达式不能改变这一点。

因此不仅没有新的输入分配给 $answer ,但在第一次迭代之后,循环中没有任何变化。所以它永远运行,打印基于相同的问题 $answer .

你需要

while (my $answer = <STDIN>) {
chomp $answer;
# ...
}

反而。

每次情况 while (...)评估新输入通过 <STDIN> 读取并分配给 $answer .然后每个新问题使用新的 $answer .请注意如何在 while 中声明变量条件所以只存在于循环体内(以及在其声明之后的条件中)。这是将其范围限制在循环内需要的地方的好方法。

文件句柄读取 <...>返回 undef当它得到时 EOF (或出错)并且循环终止。见 I/O Operators in perlop .终端用户通常可以通过 Ctrl-d 实现这一点。 .

关于perl - 如何在 Perl 中从终端获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41950624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com