hadoop小学生
精灵王
精灵王
  • 注册日期2018-09-13
  • 发帖数160
  • QQ3234520070
  • 火币360枚
  • 粉丝0
  • 关注0
阅读:3987回复:0

Hanlp分词1.7版本在Spark中分布式使用记录

楼主#
更多 发布于:2019-03-11 15:27
新发布1.7.0版本的hanlp自然语言处理工具包差不多已经有半年时间了,最近也是一直在整理这个新版本hanlp分词工具的相关内容。不过按照当前的整理进度,还需要一段时间再给自然语言处理1详细分享整理的内容。昨天正好看到的这篇关于关于1.7.0版本hanlp分词spark中的使用介绍的文章,顺便分享给大家一起学习一下!

图片:封面.jpg


以下为分享的文章内容:
HanLP分词,如README中所说,如果没有特殊需求,可以通过maven配置,如果要添加自定义词典,需要下载“依赖jar包和用户字典".
直接"java xf hanlp-1.6.8-sources.jar" 解压源码,把源码加入工程(依赖本地jar包,有些麻烦,有时候到服务器有找不到jar包的情况)
按照文档操作,在Spark中分词,默认找的是本地目录,所以如果是在driver中分词是没有问题的。但是如果要分布式分词,是要把词典目录放在HDFS上面,因为这样每台机器才可以访问到 【参考代码】
最好把新增词典放在首位第一次使用时,HanLP会把新增txt文件,生成bin文件,这个过程比较慢。但是只需要跑一次,它会把bin文件写到HDFS路径上面,第二次以后速度就快一些了。
注意到issue中说,只可以在mapPartition中使用
参考scala代码
class hadoopFileIoAdapter extends IIOAdapter {
 override def create(path: String): java.io.OutputStream = {
   val conf: Configuration = new Configuration()
   val fs: FileSystem = FileSystem.get(URI.create(path), conf)
   fs.create(new Path(path))
 }
 override def open(path: String): java.io.InputStream = {
   val conf: Configuration = new Configuration()
   val fs: FileSystem = FileSystem.get(URI.create(path), conf)
   fs.open(new Path(path))
 }
}
def myfuncPerPartition_ ( iter : Iterator [String] ) : Iterator[(Int, mutable.Buffer[String])]  = {
     println("run in partition")
     val keyWordNum = 6
     HanLP.Config.IOAdapter = new HadoopFileIoAdapter
     val ret = iter.filter(_.split(",",2).length==2)
       .map(line=>(line.split(",",2)(1).trim.hashCode, HanLP.extractKeyword(line.split(",",2)(0),keyWordNum)
         .map(str=>str.filterNot(stopChar.contains(_))).filter(w=>(w.length>1 || ( w.length==1 && white_single_word.contains(w(0))) ))
         .filterNot(stopWords.contains(_)).take(keyWordNum).distinct))
     ret
   }
//调用
raw_data.repartition(100).mapPartitions(myfuncPerPartition_)

喜欢0 评分0
DKHadoop用着还不错!
游客

返回顶部