Skip to content

Instantly share code, notes, and snippets.

@hecomi
Created January 23, 2012 16:36
Show Gist options
  • Save hecomi/1664139 to your computer and use it in GitHub Desktop.
Save hecomi/1664139 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/format.hpp>
namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;
namespace sw = qi::standard_wide;
// 結果を格納する型(2次元 string テーブル)
typedef std::vector<std::vector<std::string>> str_2d_array;
/* ------------------------------------------------------------------------- */
// Parser
// string: "(a|b|c)d(e|f)g" --> str_2d_array: { {a,b,c}, d, {e,f}, g}
/* ------------------------------------------------------------------------- */
template <typename Iterator>
bool command_parse(Iterator first, Iterator last, str_2d_array& result)
{
using sw::char_;
using qi::_1;
using qi::lit;
qi::rule<Iterator, std::string(), sw::space_type> word, words, sentence;
std::vector<std::string> buf;
word = +( char_ - '(' - '|' - ')' );
words = -lit('(')
>> ( word [phx::push_back(phx::ref(buf), _1)] % '|' )
>> -lit("|)") [phx::push_back(phx::ref(buf), "")]
>> -lit(')');
sentence = *(
words
[phx::push_back(phx::ref(result), phx::ref(buf))]
[phx::clear(phx::ref(buf))]
)
>> qi::eol;
bool r = qi::phrase_parse(first, last, sentence, sw::space);
if (!r || first != last) {
return false;
}
return true;
}
/* ------------------------------------------------------------------------- */
// main 関数(テスト用)
/* ------------------------------------------------------------------------- */
int main(int argc, char const* argv[])
{
std::string str = "(電気|ライト)(を|)(オン|オフ|つけて|消して)";
std::string::const_iterator iter = str.begin(), end = str.end();
str_2d_array sentences;
if (command_parse(iter, end, sentences)) {
std::cout << "failed" << std::endl;
return 1;
}
std::cout << "kaden.grammar" << std::endl;
std::cout << "S\t: NS_B ";
for (size_t i = 0; i < sentences.size(); ++i) {
std::cout << boost::format("WORD%1% ") % i;
}
std::cout << "NS_E\n\n";
std::cout << "kaden.voca" << std::endl;
int n = 0;
for (const auto& sentence : sentences) {
std::cout << boost::format("%% WORD%1%\n") % n++;
for (const auto& x : sentence) {
std::cout << boost::format("%1%\t%2%\n") % ( (x=="") ? "<sp>" : x ) % "d u m m y";
}
}
std::cout <<
"% NS_B\n"
"<s>\tsilB\n"
"% NS_E\n"
"<s>\tsilE\n";
return 0;
}
@hecomi
Copy link
Author

hecomi commented Jan 23, 2012

kaden.grammar
S : NS_B WORD0 WORD1 WORD2 NS_E

kaden.voca
% WORD0
電気 d u m m y
ライト d u m m y
% WORD1
を d u m m y
<sp> d u m m y
% WORD2
オン d u m m y
オフ d u m m y
つけて d u m m y
消して d u m m y
% NS_B
<s>silB
% NS_E
<s>silE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment