中国語の形態素解析

$ pip3 install jieba

import jieba.posseg as pseg

fen_cixing = pseg.cut("学习辉煌党史重温峥嵘岁月发扬延安精神奋斗新的征程")

for word, flag in fen_cixing:
	print(word, flag)

$ python3 app.py
Building prefix dict from the default dictionary …
Loading model from cache /tmp/jieba.cache
Loading model cost 0.618 seconds.
Prefix dict has been built successfully.
学习 v
辉煌 a
党史 n
重温 n
峥嵘岁月 i
发扬 v
延安精神 nr
奋斗 v
新 a
的 uj
征程 n

OK これは使えるっぽい^^
よっしゃああああああああああああああああああああ

amzn2でNLTKを動かす

$ pip3 install nltk

### 分かち書き

nltk.download('punkt')

### 品詞の取得

import nltk
nltk.download('averaged_perceptron_tagger')
# -*- coding:utf-8 -*-

import nltk
nltk.download('punkt')
s = "The Brooklyn Nets appeared to be well on their way to taking a 3-0 series lead over the Boston Celtics Friday night, as they erupted out of the TD Garden gates on a 19-4 run in the first four minutes of action."
morph = nltk.word_tokenize(s)
print(morph)

$ python3 app.py
[nltk_data] Downloading package punkt to /home/vagrant/nltk_data…
[nltk_data] Package punkt is already up-to-date!
[‘The’, ‘Brooklyn’, ‘Nets’, ‘appeared’, ‘to’, ‘be’, ‘well’, ‘on’, ‘their’, ‘way’, ‘to’, ‘taking’, ‘a’, ‘3-0’, ‘series’, ‘lead’, ‘over’, ‘the’, ‘Boston’, ‘Celtics’, ‘Friday’, ‘night’, ‘,’, ‘as’, ‘they’, ‘erupted’, ‘out’, ‘of’, ‘the’, ‘TD’, ‘Garden’, ‘gates’, ‘on’, ‘a’, ’19-4′, ‘run’, ‘in’, ‘the’, ‘first’, ‘four’, ‘minutes’, ‘of’, ‘action’, ‘.’]

うおおおおおおおおおおおおおお
ガチSugeeeeeeeeeeeeee

import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
s = "The Brooklyn Nets appeared to be well on their way to taking a 3-0 series lead over the Boston Celtics Friday night, as they erupted out of the TD Garden gates on a 19-4 run in the first four minutes of action."
morph = nltk.word_tokenize(s)
pos = nltk.pos_tag(morph)
print(pos)

$ python3 app.py
[nltk_data] Downloading package punkt to /home/vagrant/nltk_data…
[nltk_data] Package punkt is already up-to-date!
[nltk_data] Downloading package averaged_perceptron_tagger to
[nltk_data] /home/vagrant/nltk_data…
[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.
[(‘The’, ‘DT’), (‘Brooklyn’, ‘NNP’), (‘Nets’, ‘NNPS’), (‘appeared’, ‘VBD’), (‘to’, ‘TO’), (‘be’, ‘VB’), (‘well’, ‘RB’), (‘on’, ‘IN’), (‘their’, ‘PRP$’), (‘way’, ‘NN’), (‘to’, ‘TO’), (‘taking’, ‘VBG’), (‘a’, ‘DT’), (‘3-0’, ‘JJ’), (‘series’, ‘NN’), (‘lead’, ‘NN’), (‘over’, ‘IN’), (‘the’, ‘DT’), (‘Boston’, ‘NNP’), (‘Celtics’, ‘NNPS’), (‘Friday’, ‘NNP’), (‘night’, ‘NN’), (‘,’, ‘,’), (‘as’, ‘IN’), (‘they’, ‘PRP’), (‘erupted’, ‘VBD’), (‘out’, ‘IN’), (‘of’, ‘IN’), (‘the’, ‘DT’), (‘TD’, ‘NNP’), (‘Garden’, ‘NNP’), (‘gates’, ‘NNS’), (‘on’, ‘IN’), (‘a’, ‘DT’), (’19-4′, ‘JJ’), (‘run’, ‘NN’), (‘in’, ‘IN’), (‘the’, ‘DT’), (‘first’, ‘JJ’), (‘four’, ‘CD’), (‘minutes’, ‘NNS’), (‘of’, ‘IN’), (‘action’, ‘NN’), (‘.’, ‘.’)]

英語は誰でも意味わかるからな。
英語じゃなくて、中国語で分かち書きをやりたいな。

amazon linux2で何としてもPolyglotを動かしたい

$ sudo yum install python3-devel
$ pip3 install pyicu
$ pip3 install pycld2
$ pip3 install morfessor

$ python3 app.py
Traceback (most recent call last):
File “app.py”, line 3, in
from polyglot.detect import Detector
File “/home/vagrant/.local/lib/python3.7/site-packages/polyglot/detect/__init__.py”, line 1, in
from .base import Detector, Language
File “/home/vagrant/.local/lib/python3.7/site-packages/polyglot/detect/base.py”, line 11, in
from icu import Locale
ImportError: cannot import name ‘Locale’ from ‘icu’ (/home/vagrant/.local/lib/python3.7/site-packages/icu/__init__.py)

何故だ?
とりあえずnltkを使うか。。。

英文の自然言語解析

日本語の形態素解析は、MeCab, ChaSen, Kuromojiあたりが有名
英語だと、TreeTagger, NLTK, Polyglotなどがある

### Polyglotの特徴
– Tokenization, Language detection, Named Entity Recognition, Part of Speech Tagging, Sentiment Analysis, Word Embeddings, Morphological analysis, Transliteration
– コマンドラインから直接叩ける
$ polyglot detect –input testdata/cricket.txt
– GPLv3 license

$ mkdir polyglot
$ cd polyglot

$ sudo yum install libicu-devel
$ pip3 install numpy
$ pip3 install polyglot
$ pip3 install morfessor
$ pip3 install six
$ pip3 install icu

### モデルのインストール
Polyglotは使用する言語に応じてモデルをダウンロードする必要がある
$ sudo yum install python3-tkinter

# -*- coding:utf-8 -*-

from polyglot.detect import Detector

t = "Hé ! bonjour, Monsieur du Corbeau.Que vous êtes joli ! Que vous me semblez beau !"
detector = Detector(t)
print(detector)

$ python3 app.py
Traceback (most recent call last):
File “app.py”, line 3, in
from polyglot.detect import Detector
File “/home/vagrant/.local/lib/python3.7/site-packages/polyglot/detect/__init__.py”, line 1, in
from .base import Detector, Language
File “/home/vagrant/.local/lib/python3.7/site-packages/polyglot/detect/base.py”, line 11, in
from icu import Locale
ImportError: cannot import name ‘Locale’ from ‘icu’ (/home/vagrant/.local/lib/python3.7/site-packages/icu/__init__.py)

うーん、環境構築がうまく行かないな。。。

amazon linux2にmecab辞書をインストールしたい

$ mkdir mecab-ipadic
$ cd mecab-ipadic

$ wget ‘https://drive.google.com/uc?export=download&id=0B4y35FiV1wh7MWVlSDBCSXZMTXM’ -O mecab-ipadic-2.7.0-20070801.tar.gz
$ tar zxvf mecab-ipadic-2.7.0-20070801.tar.gz
$ cd mecab-ipadic-2.7.0-20070801
$ ./configure –with-mecab-config=/opt/mecab/bin/mecab-config –with-charset=utf8
$ make
/mecab-dict-index -d . -o . -f EUC-JP -t utf8
make: /mecab-dict-index: Command not found
make: *** [matrix.bin] Error 127

ん? 何故だ?

$ git clone –depth 1 https://github.com/neologd/mecab-ipadic-neologd.git
$ ./mecab-ipadic-neologd/bin/install-mecab-ipadic-neologd -n -a -y
terminate called after throwing an instance of ‘std::bad_alloc’

$ sudo /bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
$ sudo /sbin/mkswap /var/swap.1
$ sudo /sbin/swapon /var/swap.1
$ free

$ ./mecab-ipadic-neologd/bin/install-mecab-ipadic-neologd -n -a -y

mecabではなく、英語でやるか。。

amzn linux2で自然言語処理

$ mecab –version
mecab of 0.996
$ pip3 install install natto-py

### 全体フロー
1. 評価用のデータ作成
2. 評価テキストが入ってくる
3. 1文毎に分解してmecabを使って品詞分解
4. 用意してあった用語、名詞別リストと照らし合わせ、それぞれの点数を足し合わす
5. 上記の4を文の数だけ繰り返す

### コード
1. 設定コード
2. データを読み込むコード
3. 読み込んだデータを処理
4. 処理したデータを出力

import codecs, csv
import re
from natto import MeCab
import os

def nlp(data): nm = MeCab()

negaposi_dic = getNegaPosiDic()

	sentenses = re.split("[。!!♪♫★☆>??()w]", data)

	try: for sentense in sentenses:

	negaposi = 0 result_all = nm.parse(sentense)

for word in result_words: try: word_toarray = re.split('[\t,]', word) if word_toarray[7] in negaposi_dic: negaposi = int(negaposi_dic[word_toarray[7]])

except Exception as e: print('%r' % e, flush=True) print(data, flush=True) return points

csvデータセットの中身

$ python3 app.py
美味しく炊けます。 安定の象印! 保温も良く臭くならないので良いです。 食べ過ぎ注意ですね

ERROR:natto.environment:MeCab dictionary charset not found

$ mecab -D
param.cpp(69) [ifs] no such file or directory: /usr/local/lib/mecab/dic/mecab-ipadic-neologd/dicrc

単純パーセプトロン

線形分類器の出力を-100, -200などの数値ではなく、確率で出力する
W^TX

0~1の間の値を取るようにシグモイド関数(sigmoid function)を使う
a = 1 / 1+exp(-a)
a = w1x1 + w2x2 + w3x3 + w4x4

このような分類器を単純パーセプトロンと呼び、もっとも簡単なニューラルネットワークである
どのような確率で出力されるかは特徴ベクトルxと重みベクトルwによって決まる

クロスエントロピー: 2つの確率分布の間に定義される尺度

なるほど^^

為替レートをOpenExchangeRateのAPIで取得したい

外為オンラインでjsonで提供している
https://www.gaitameonline.com/rateaj/getrate
JPYで提供している通貨ペアは以下の通り
CADJPY, AUDJPY, NZDJPY, ZARJPY, CHFJPY, EURJPY, USDJPY, GBPJPY

$url = "https://www.gaitameonline.com/rateaj/getrate";
$content = file_get_contents($url);
$data = json_decode($content, true);

echo "<pre>";
var_dump($data);
echo "</pre>"; 

って、CNYないやんけ。。。🤮🤮🤮
ということで、open exchange rateのapiを使ってみたいと思う。

### open exchange rates
https://openexchangerates.org/
freeプランで登録して、APP IDを取得します。

$appId = '*';
$baseURL = 'https://openexchangerates.org/api/latest.json?app_id=' . $appId ;

$curlHandle = curl_init();

$options = [
	CURLOPT_URL => $baseURL,
	CURLOPT_HEADER => false,
	CURLOPT_RETURNTRANSFER => true
];

curl_setopt_array($curlHandle, $options);

$results = curl_exec($curlHandle);
$resultsData = json_decode($results);

$usdcny = $resultsData->rates->CNY;
$usdjpy = $resultsData->rates->JPY;

echo $usdcny . "<br>";
echo $usdjpy;

なるほど〜

radioボタンの選択状況によってHTMLの表示を変えたい

### radioボタンの選択状況の取得

<form method="" action="">
		<label for="en"><input type="radio" id="en" name="lang" value="1" checked>英語</label>
		<label for="cn"><input type="radio" id="cn" name="lang" value="2">中国語(簡体字)</label>
	</form>
	<script>
		window.addEventListener('DOMContentLoaded', function(){
			var inputs = document.querySelectorAll("input[name=lang]");
			for(var element of inputs){
				element.addEventListener('change', function(){
					if(this.checked){
						console.log(this.value);
					}
				});
			}
		})
	</script>

値を取得できているのがわかります。

表示自体を変えるには display noneとdisplay blockを切り分けます。

	<label>
	  <input class="js-check" type="radio" name="lang" value="1" onclick="formSwitch()" checked>英語
	</label>
	<label>
	  <input class="js-check" type="radio" name="lang" value="2" onclick="formSwitch()">中国語(簡体字)
	</label>
	<br><br>
	<span id="en">Name</span>
	<span id="cn">产品名称</span>


	<script>
		var en = document.getElementById('en');
		var cn = document.getElementById('cn');
		cn.style.display = "none";

	    function formSwitch() {
	        check = document.getElementsByClassName('js-check')
	        if (check[0].checked) {
	            cn.style.display = "none";
	            en.style.display = "block";
	        } else if (check[1].checked) {
	            en.style.display = "none";
	            cn.style.display = "block";
	        } 
	    }
	    window.addEventListener('load', formSwitch());
	</script>

うん、これでOKかな。

国ごとの電話コードのJavaScriptライブラリ「International Telephone Input」を使う

国際電話の電話コードの入力の助けになる様なJSライブラリがないか探した
例えば、日本の場合は国際電話の場合 「+81 -*」となる
どうやら、jQueryでInternational Telephoneというのがあるらしい
https://github.com/jackocnr/intl-tel-input

GithubからzipファイルをDLして、build側のフォルダからintlTelInput.css と intlTelInput.jsを使います。
src側のフォルダからintlTelInput.jsを使うと、「window.intlTelInput is not a function」とエラーになるので注意が必要

<link rel="stylesheet" href="css/intlTelInput.css">
// 省略
                <div class="form-group">
                  <label for="tel">電話番号</label>
                  <input type="tel" name="tel" id="mobile-number" class="form-control col-md-6">
                </div>
// 省略
  <script src="js/jquery.min.js"></script>
  <script src="js/intlTelInput.js"></script>
  <script>
  var $input = document.querySelector("#mobile-number");
  window.intlTelInput($input, {
      defaultCountry: "us",
    });
  </script>

OK、顧客登録側はほぼほぼ出来たかな^^