1. 程式人生 > >如何在創建hive表格的python代碼中導入外部文件

如何在創建hive表格的python代碼中導入外部文件

quest 集群 shel 導入 數據分析入門 transform add sin key

業務場景大概是這樣的,我要對用戶博文進行分詞(這個步驟可以看這篇文章如何在hive調用python的時候使用第三方不存在的庫-how to use external python library in hadoop)
然後在對每條博文進行分詞之後呢,我需要做的就是對分詞之後的結果去除停用詞,但是在公司hadoop集群是是沒有我們所需要的停用詞文件的,其實解決這個問題很類似我上面列出來的文章,就是如果在hive的自定義函數中使用我們自己的文件或者包

解決辦法大概是這樣:
首先在shell腳本中加入 add file ./stop_word.txt;

function zida(){
cat <<EOF
add file ./jieba.mod;
add file ./stop_word.txt;
add file ./zida.py;

    select transform(tmp.*) using 'python zida.py test'
    AS uid,bowen
    FROM(
        select *  from hive_table)tmp
EOF
}

hive -e "`zida`"
echo "zida"

然後在python腳本中加入對應代碼:

import io
stopwords = [line.strip() for line in io.open('stop_word.txt','r',encoding='utf-8').readlines()]

在這個辦法中,會出現報錯,原因就是公司python運行環境比較老舊,所以在讀取中文文本的時候會出現問題:
代碼是這樣的

stopwords = [line.strip() for line in open('stop_word.txt','r',encoding='utf-8').readlines()]

出現報錯:
‘encoding‘ is an invalid keyword argument for this function

解決辦法如下:

import io
stopwords = [line.strip() for line in io.open('stop_word.txt','r',encoding='utf-8').readlines()]

這個問題的解決是參考的這裏

參考鏈接:
關於這個方法一個很好的總結-hive+python數據分析入門
Accessing external file in Python UDF

如何在創建hive表格的python代碼中導入外部文件