我正在创建一个圣经搜索。圣经搜索的问题是,人们经常输入不同类型的搜索,我需要相应地对它们进行划分。因此,我认为最好的开始方法是删除所有空格,然后遍历那里的字符串。不同类型的搜索可以是:
Genesis 1:1
-创世纪第1章,第1节
1 Kings 2:5
-1列王记第二章第五节
Job 3
-作业第3章
Romans 8:1-7
-罗马书第8章1至7节
1 John 5:6-11
-1约翰福音第5章第6- 11节。
我不是太阶段性的不同类型的搜索,但如果有人可以找到一个更简单的方法来做这件事,或知道的一个伟大的方法,然后请告诉我如何做!
谢谢
发布于 2012-10-30 23:32:46
这里要做的最简单的事情是编写一个正则表达式来捕获文本,然后解析捕获的内容以查看您得到了什么。首先,让我们假设您有自己的测试平台:
$tests = array(
'Genesis 1:1' => 'Genesis Chapter 1, Verse 1',
'1 Kings 2:5' => '1 Kings Chapter 2, Verse 5',
'Job 3' => 'Job Chapter 3',
'Romans 8:1-7' => 'Romans Chapter 8, Verses 1 to 7',
'1 John 5:6-11' => '1 John Chapter 5, Verses 6 to 11'
);
所以,从左到右,你有:
因此,我们可以编写一个正则表达式来匹配所有这些情况:
((?:\d+\s)?\w+)\s+(\d+)(?::(\d+(?:-\d+)?))?
现在看看我们从正则表达式中得到了什么:
foreach( $tests as $test => $answer) {
// Match the regex against the test case
preg_match( $regex, $test, $match);
// Ignore the first entry, the 2nd and 3rd entries hold the book and chapter
list( , $book, $chapter) = array_map( 'trim', $match);
$output = "$book Chapter $chapter";
// If the fourth match exists, we have a verse entry
if( isset( $match[3])) {
// If there is no dash, it's a single verse
if( strpos( $match[3], '-') === false) {
$output .= ", Verse " . $match[3];
} else {
// Otherwise it's a range of verses
list( $start, $end) = explode( '-', $match[3]);
$output .= ", Verses $start to $end";
}
}
// Here $output matches the value in $answer from our test cases
echo $answer . "\n" . $output . "\n\n";
}
您可以在this demo中看到它的工作方式。
发布于 2012-10-30 22:17:56
我想我明白你在这里问的是什么。您想要设计一种算法来提取信息(例如,书名、章节、诗句)。
在我看来,这是一个模式匹配的工作(例如,正则表达式),因为您可以定义模式,为所有有意义的场景提取数据并从中开始工作。
实际上,可能存在相当多的变体--也许您还应该看看自然语言处理。对名称进行模糊字符串匹配可以提供更好的结果(例如,人们拼写错误的书名)。
祝你好运
发布于 2012-10-30 22:22:15
尝试一些基于preg_match_all的东西,比如:
$ php -a
Interactive shell
php > $s = '1 kings 2:4 and 1 sam 4-5';
php > preg_match_all("/(\\d*|[^\\d ]*| *)/", $s, $parts);
php > print serialize($s);
https://stackoverflow.com/questions/13140721
复制相似问题