码迷,mamicode.com
首页 > 其他好文 > 详细

Perl 简单的猜单词脚本

时间:2017-02-03 23:02:22      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:res   pen   --   whether   com   提取   case   code   redo   

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 简单的猜单词脚本

标签:res   pen   --   whether   com   提取   case   code   redo   

原文地址:http://www.cnblogs.com/Onlynagesha/p/6363645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!