标签:
使用 php 封装一个方法:实现将数组内单词进行造句,并满足:1、可指定生成的句子数量;2、可指定可使用的单词数量范围;3、可指定句子中必须包含的单词;4、生成的句子不可重复;5、性能高效占用内存小
function generateSentences(array $words, int $sentenceCount, array $wordRange, array $mustIncludeWords = []) {
$sentences = [];
$wordCount = count($words);
$usedSentences = [];
if ($sentenceCount <= 0 || $wordCount == 0) {
return $sentences;
}
// 检查必含单词是否在词库中
foreach ($mustIncludeWords as $word) {
if (!in_array($word, $words)) {
throw new Exception("必含单词 $word 不在词库中");
}
}
while (count($sentences) < $sentenceCount) {
// 从可使用的单词数量范围内随机选择一个数量
$wordCountInSentence = rand($wordRange[0], $wordRange[1]);
// 随机选择单词
$selectedWords = [];
for ($i = 0; $i < $wordCountInSentence; $i++) {
$selectedWords[] = $words[rand(0, $wordCount - 1)];
}
// 添加必须包含的单词
foreach ($mustIncludeWords as $word) {
if (!in_array($word, $selectedWords)) {
$selectedWords[array_rand($selectedWords)] = $word;
}
}
// 拼接成句子
$sentence = implode(' ', $selectedWords);
// 去重
if (!in_array($sentence, $usedSentences)) {
$sentences[] = $sentence;
$usedSentences[] = $sentence;
}
// 检查是否达到最大可能组合数
if (count($usedSentences) >= pow($wordCount, $wordRange[1])) {
break;
}
}
return $sentences;
}
// 示例用法
$words = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape'];
$sentenceCount = 5;
$wordRange = [3, 5];
$mustIncludeWords = ['date', 'fig'];
$sentences = generateSentences($words, $sentenceCount, $wordRange, $mustIncludeWords);
print_r($sentences);
PHP
说明:
-
输入参数:
$words
:用于生成句子的单词数组。$sentenceCount
:要生成的句子数量。$wordRange
:句子中单词数量的范围,数组形式如[最小单词数, 最大单词数]
。$mustIncludeWords
:句子中必须包含的单词数组。
-
功能实现:
- 首先检查必含单词是否在单词库中,如果不在则抛出异常。
- 使用
rand
函数随机生成句子的单词数量,确保在指定范围内。 - 随机选取单词生成句子并保证包含必含单词。
- 通过
implode
函数将数组转换成句子,并通过去重数组避免重复句子。 - 检查是否达到组合的最大值以防止进入无限循环。
-
注意:
- 此实现主要针对小型数据集。对于非常大的数据集,可能需要优化随机选择部分以提高效率。
- 可使用
array_flip
和array_unique
来进一步优化去重和检查步骤。
该方法应能在大多数情况下高效地生成符合要求的句子。
标签: 来源:
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。