Hadoop上使用Darts词典
1.在map class的setup函数中load词典,调用Darts.LoadDict函数
protected void setup(Context context) throws IOException, InterruptedException
{
if (!Darts.LoadDict("xxx_utf8.dict"))
return;
}
2.在map或者reduce class函数中使用词典,调用Darts.IsInDict函数
protected void map(Writable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString().trim();
if (Darts.IsInDict(line.toString()))
{
context.write(new Text(line.toString()), new LongWritable(1));
}
}
注意!一定要确定line中用的是utf8编码格式的字符。而且,我看JNI(jni.h)中的接口函数,似乎字符串值能够用utf8的;或者即便是用它的jchar转换编码,也比较麻烦。这个是jni.h中的接口片段:
jstring (JNICALL *NewStringUTF)
(JNIEnv *env, const char *utf);
jsize (JNICALL *GetStringUTFLength)
(JNIEnv *env, jstring str);
const char* (JNICALL *GetStringUTFChars)
(JNIEnv *env, jstring str, jboolean *isCopy);
void (JNICALL *ReleaseStringUTFChars)
(JNIEnv *env, jstring str, const char* chars);
在实际实现libDarts.so的时候,调用的是GetStringUTFChars。为避免麻烦,也就统一用utf8好了。如果不确定读取数据的编码,可以用以下方式转换编码:
String line = value.toString().trim();
String line_utf8 = new String (line.getBytes("UTF-8"), "UTF-8");
if (Darts.IsInDict(line_utf8.toString()))
{
context.write(new Text(line_utf8.toString()), new LongWritable(1));
}
