**Note! It is intended for environments where python, mamp, and gensim are installed. If you can't, please install it. ** ** ** Also, instead of learning word2vec, just look for similar words. ** **
First, connect to python from php.
Put this in php ~! The code exec can access the command line from php. (The same one as the mac terminal.)
<?php
exec('ls')
?>
Use this to run python with word2vec written on it. For example ..., you can run a python file like test.py from php.
<?php
exec('python test.py')
?>
Then bring the data to look for similar words in word2vec. Let's download the zip. http://www.cl.ecei.tohoku.ac.jp/~m-suzuki/jawiki_vector/ I will use this later.
Next, on the python side, create a new python file. Write like this. This is ok ~! Please answer the zip you downloaded earlier and place it nearby. That is "entity_vector / entity_vector.model.bin". ** (If you do not delete the commented out part in Japanese now, an error will occur when reading, so please delete it! (Maybe you can read it if you devise it. I think there is something.)) **
I have to pass the path with sys.path as follows .. I get the error "Import Error: No module named'gensim'". This means that the location to look for the module set in mamp is different. So let's find the path of gensim already installed in mac in the terminal. (Pip show gensim)
word2vec.py
#I can import gensim models with python on a mac terminal, but there is no path on mamp.
#So sys.I will enter the path with path.
import sys
sys.path.append('path')
#In the "Path" section above, enter the absolute path to look up next. (Example:/Users/Taro/anaconda3/lib/python3.6/site-packages)
#Below is the code that executes word2vec.
#Look for words that are similar to "graphic".
from gensim.models import KeyedVectors
model_dir = 'entity_vector/entity_vector.model.bin'
model = KeyedVectors.load_word2vec_format(model_dir, binary=True)
results = model.similar_by_vector("graphic", topn=10, restrict_vocab=None)
for result in results:
print(result)
Now back to php. Execute the command and execute the python file with exec (). The second argument is the result. In the third argument, if there is an error, something will be returned. Now .. the result is ..
index.php
$command = 'python wd2vc.py';
exec($command, $output, $return_var);
var_dump($output, $return_var);
I got it! !! Words similar to "graphic" are output as an array. You did it!
Reference article: PHP --Summary of the relationship between exec () error handling and standard error output https://qiita.com/smd8122/items/65b552f1d53bfb7fad9a I was a little addicted to using Mecab from PHP in MAMP! https://dbym4820.hatenablog.com/entry/2017/10/18/171259
Recommended Posts