在php中生成字典中的随机单词

时间:2011-12-24 13:23:40

标签: php random dictionary word

请看一下这个链接:Random entry from dictionary

那个例子是C#,但是,我的问题是如何从php中的字典生成一个随机条目?

php是否具有字典的内置函数,或者我是否需要API或其他内容才能执行此操作?

3 个答案:

答案 0 :(得分:1)

如果我理解正确的话,

array_rand可能会做你想要的。

$array = array(
    'key' => 'value',
    'key2' => 'value2',
    // etc
);
$randomKey = array_rand($array); // get a random key
echo $array[$randomKey]; // get the corresponding value

答案 1 :(得分:0)

为了完成Tom的回答,我在我的一个项目中有类似的需求,这里我的类是字典直接嵌入PHP文件中的棘手功能。

/**
 * Generate bunch of english Lorem Ipsum.
 * 
 * 
 * 
 * @category Tool
 * @package Tool
 * @version 
 */
class RandomWord
{
    /**
     * List of words in the dictionnary 
     * 
     * @var array
     */
    static private $_words = array();

    /**
     * Load the dictionary. 
     * 
     * This would load the dictionnary embedded in this PHP file
     */
    static public function loadDictionnary()
    {
        $fp = fopen(__FILE__, 'r');
        $halted = false;

        while (($line = fgets($fp, 4096)) !== false) {
            if ($halted == false) {
                if (preg_match('/__halt_compiler\(\);/', $line)) {
                    $halted = true;
                }    
            } else {
                list($word, $dummy) = explode("\t", $line);
                array_push(self::$_words, $word);    
            }
        }

        fclose($fp);
    }

    /**
     * Pickup a random word from the dictionnary
     * 
     * @return string
     */
    static public function random()
    {
        if (!count(self::$_words)) {
            self::loadDictionnary();
        }
        return self::$_words[array_rand(self::$_words)];
    }

    /**
     * Generate a number of paragraph of random workds 
     * 
     * @param integer $numberOfWords
     * @param integer $paragraph
     * @return string
     */
    static public function loremIpsum($numberOfWords = 20, $paragraph = 1)
    {
        $ret = '';
        for ($i = 0; $i < $paragraph; $i++) {
            for ($v = 0; $v < $numberOfWords; $v++) {
                $ret .= self::random() . ' ';
            }
            if ($paragraph > 1) {
                $ret .= "\n";
            }
        }

        $ret = substr($ret, 0, strlen($ret) - 1);

        return $ret;
    }
}

__halt_compiler();
's gravenhage   |h
'tween  |v
'tween decks    |v
.22 |N
0   |NA
1   |NA
1-dodecanol |N
1-hitter    |N
10  |NA
100 |NA
1000    |NA
10000   |N
100000  |N
1000000 |N
1000000000  |N
1000000000000   |N
1000th  |A
100th   |A
10th    |A
11  |NA
11-plus |N

答案 2 :(得分:0)

从GitHub,您可以download包含每行中所有词典单词的文本文件。完整指南就在这里 - Get random word from English dictionary in PHP tutorial

下面是随机选择一行并获取该行词的PHP代码:

<?php
$file = "words_alpha.txt";
$file_arr = file($file);
$num_lines = count($file_arr);
$last_arr_index = $num_lines - 1;
$rand_index = rand(0, $last_arr_index);
$rand_text = $file_arr[$rand_index];
echo $rand_text;
?>

来源: Get random word from English dictionary in PHP