首页 > 代码库 > Perl 简单的猜单词脚本
Perl 简单的猜单词脚本
Last update:17/02/03
输入格式:每行一个句子,关键词用[]标示,如:
If you are [suspicious] of sth, you don‘t know whether it is true or possible.
If you [strive] to do sth, you make a great effort to achieve it.
He commited [suicide] in despair, leaving his wife alone.
According to all the evidence we have got, he is [presumably] the criminal.
[Toxic] substance is contained in rotten foods.
脚本从文件中读入上述信息,利用正则表达式提取关键词
代码如下:
1 #!/usr/bin/perl 2 use 5.018; 3 4 my @word; 5 my @sentence; 6 7 my $pattern = "[A-Za-z\-]"; 8 9 say "Input the file name:"; 10 chomp (my $fileName = <STDIN>); 11 open FIN, $fileName; 12 13 while (<FIN>) 14 { 15 chomp; 16 if (/ \[ (${pattern}+) \] /x) 17 { 18 my $curWord = $1; 19 my $underline = ($curWord =~ s/$pattern/_/rg); 20 push @word, $curWord; 21 push @sentence, (s/ \[ $curWord \] /$underline/rx); 22 } 23 } 24 close FIN; 25 26 my $id; 27 my ($rightCnt, $wrongCnt); 28 say "\nGuess the word according to context."; 29 say "Hint: Case of letters does not matter."; 30 say "Hint: you can input a question mark to give up."; 31 &getNext; 32 33 while (1) 34 { 35 chomp (my $ans = <STDIN>); 36 if ($ans =~ /\b $word[$id] \b/xi) 37 { 38 printf "Right! Right/Wrong = %d/%d\n", ++$rightCnt, $wrongCnt; 39 &getNext; 40 } 41 elsif ($ans eq "?") 42 { 43 printf "Give up. Right/Wrong = %d/%d\n", --$rightCnt, ++$wrongCnt; 44 say "The answer is: $word[$id]"; 45 &getNext; 46 } 47 else 48 { 49 say "Wrong!"; 50 ++$wrongCnt; 51 redo; 52 } 53 } 54 55 sub getNext 56 { 57 state $N = 0; 58 $id = int (rand @word); 59 printf "Problem #%d: %s (%d words)\n", ++$N, $sentence[$id], length $word[$id]; 60 }
Perl 简单的猜单词脚本
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。