我发现了一个名为 mecab 的软件,它基本上读取一个字符串并将单词分类为名词、动词等。我想做的是使用谷歌搜索 API 将搜索功能放在我的页面上,所以每当我查找位置时,例如牛津街,将显示一些结果,mecab 将单独处理每个结果并完成其工作。
我坚持的是我不知道如何将这些结果提供给 mecab。
以下是代码:
<html>
<head></head>
<body>
<script type="text/javascript" src="http://www.google.com/jsapi?key=AIzaSyBX85AAhYSkh66lk8i2VBSqVJSY_462zGM"></script>
<script type="text/javascript">
function OnLoad()
{
// Create Search Control
var searchControl = new google.search.SearchControl();
// Add searcher to Search Control
searchControl.addSearcher( new google.search.WebSearch() );
searchControl.draw( document.getElementById( 'content' ) );
// Execute search
searchControl.execute( '新宿' );
}
// Load Google Search API
google.load( 'search', '1' );
google.setOnLoadCallback( OnLoad );
</script>
<div id="content">Loading...</div>
<?php
define('Mecab_Encoding', 'SJIS');
define('Mecab_ResultEncoding', 'UTF-8');
define('MeCab_Path', 'mecab.exe');
function morph_analysis($text) {
$text = mb_convert_encoding($text, Mecab_Encoding, Mecab_ResultEncoding);
$descriptorspec = array (
0 => array ("pipe", "r"), // stdin
1 => array ("pipe", "w") // stdout
);
$process = proc_open(MeCab_Path, $descriptorspec, $pipes);
if (is_resource($process)) {
// Feed string to macab
fwrite($pipes[0], $text);
fclose($pipes[0]);
// Read the string
while (!feof($pipes[1])) {
$result .= fread($pipes[1], 4096);
}
fclose($pipes[1]);
proc_close($process);
$result = mb_convert_encoding($result, Mecab_ResultEncoding, Mecab_Encoding);
$lines = explode("\r\n", $result);
$res = array();
foreach($lines as $line) {
if(in_array(trim($line), array('EOS', ''))) {continue;}
$s = explode("\t", $line);
$word = $s[0];
$words = explode(',', $s[1]);
if ($words[0] == "名詞"){
$res[] = array(
'word' => $word,
'class' => $words[0],
'detail1' => $words[1],
'detail2' => $words[2],
'detail3' => $words[3],
'conjugation1' => $words[4],
'conjugation2' => $words[5]
);
}
}
return $res;
} else {
return false;
}
}
$text ="今日はいい天気です。";
$result = morph_analysis($text);
echo "<pre>";
print_r($result);
echo "</pre>";
?>
</body>
</html>