Pythonで自然言語処理(mecab)

$ python3 –version
Python 3.6.8
$ pip3 –version
pip 9.0.3 from /usr/lib/python3.6/site-packages (python 3.6)

$ sudo pip3 install mecab-python3
$ sudo pip3 install unidic-lite

単語と単語を分けるのを分かち書きという
$ python3
>>> import MeCab
>>> wakati=MeCab.Tagger(“-Owakati”)
>>> sentence_wakati = wakati.parse(“私は今システム開発を行なっています”).split()
>>> print(sentence_wakati)
[‘私’, ‘は’, ‘今’, ‘システム’, ‘開発’, ‘を’, ‘行なっ’, ‘て’, ‘い’, ‘ます’]

ん?
“行なって” + “います” が正の様に思うが。。

自然言語処理ってことは、検索エンジン周りかチャットボット関連か。
もしくは文章の中から特定のキーワードを見つける e.g. 技術トレンドが入っている用語
RSSから、自然言語処理で内容を評価して、カテゴライズを自動化する など

何をやるかやな。

D4を更に理解しよう

ORDA: Object Relational Data Access

Table, field, and relation names are mapped to object property names. Make sure that such names comply with general object naming rules, as explained in the object naming conventions section.
A datastore only references tables with a single primary key. The following tables are not referenced:
Tables without a primary key
Tables with composite primary keys.
BLOB type attributes are not managed in the datastore. BLOB type attributes are returned as Null in entities and cannot be assigned.

$mydatastore:=OB Copy(ds) 
 ARRAY TEXT($prop;0)
 OB GET PROPERTY NAMES(ds;$prop)

こりゃハードル高いというか、時間がかかるな。。

D4を使ってみよう

4D Product DownloadのページからDLします。
https://us.4d.com/product-download/Feature-Release

4D Documentationを見ながらやっていきます。

Projectを作ります。

Architecture of project
– components
– data
L logs
L settings
– documentation
– plugins
– project
L derivedData
L sources
L trash
– resources
– settings
– userPreferences.username
– WebFolder

Project folder
– sources
L classes, databaseMethods, Methods, Forms, TableForms, Triggers
– DerivedData
– Trash

${appname}.4DProject: 4D, 4D server

設定ファイルはXMLやJSONで書かれてますね。
メソッドを作って、ドキュメントを書く。

<!-- This method returns a different logo depending on the size parameter -->


GetLogo (size) -> logo


| Parameter | Type   | in/out | Description |
| --------- | ------ | ------ | ----------- |
| size      | Longint | in | Logo style selector (1 to 5)  |
| logo      | Picture | out | Selected logo |


## Description

This method returns a logo of a specific size, depending on the value of the *size* parameter value.
1 = smallest size, 5 = largest size.

## Example

C_PICTURE($logo)
C_LONGINT($size)

//Get the largest logo
$logo:=GetLogo(5)

ちょっとだけ理解した。

JANコードの作成手順

JANコードは、どの事業者のどの商品かを表す世界共通の商品識別番号
日本では45もしくは49から始まる9桁の事業者番号から始まる

JANコード(標準13桁)
①最初の9桁:GS1事業者コード ②次の3桁:商品アイテムコード ③最後の1桁:チェックデジット(入力ミス防止用)

JANコードの作成手続き
– GS1事業者コードの新規登録手続き
– 商品アイテムコードの作成(001から順番に作成)

チェックデジットの計算方法
1. 全ての偶数桁の数字を加算
2. 1の結果を3倍
3. 全ての奇数桁の数字を加算
4. 2の結果と3の結果を加算
5. 4の結果の下1桁の数字を10から引いたものがチェックデジット

JANシンボルを印刷

なるほどー
プログラムでできるのね。

[centos8] chronyで時刻同期

vagrant、centos8で時刻がおかしい。

# date
Fri Mar 19 06:32:40 JST 2021

ん? 日付も時刻も違う。。。
$ sudo vi /etc/chrony.conf

#pool 2.centos.pool.ntp.org iburst
server ntp1.jst.mfeed.ad.jp iburst
server ntp2.jst.mfeed.ad.jp iburst
server ntp3.jst.mfeed.ad.jp iburst

# Allow NTP client access from local network.
#allow 192.168.0.0/16
allow 192.168.34.10

# chronyc sources
210 Number of sources = 4
MS Name/IP address Stratum Poll Reach LastRx Last sample
===============================================================================
^* ntp1.jst.mfeed.ad.jp 2 6 17 4 +10ms[ +13ms] +/- 86ms
^+ ntp2.jst.mfeed.ad.jp 2 6 17 5 +2838us[+5730us] +/- 95ms
^+ ntp3.jst.mfeed.ad.jp 2 6 17 5 -5627us[-2734us] +/- 104ms
^? ntp-k1.nict.jp 0 6 0 – +0ns[ +0ns] +/- 0ns
# date
Sat Mar 20 08:04:11 JST 2021

ふう
ここで躓いたらエンジニア終了だな

スクレイピングでページが更新されたかのスクリプト

$file_name = 'amzn.txt';
$fp = fopen($file_name,'w');

foreach($names as $n){
	fputs($fp, $n. "\n");
}
fclose($fp);

– copyで amzn_cp.txt を作ります。
– file_get_contents()で中身を取得して比較

copy('amzn.txt', 'amzn_cp.txt');

// スクレイピング

$file_name = 'amzn.txt';
$fp = fopen($file_name,'w');

foreach($names as $n){
	fputs($fp, $n. "\n");
}
fclose($fp);

$old = file_get_contents('amzn.txt');
$new = file_get_contents('amzn_cp.txt');

if($old !== $new){
	echo "changed";
     // 更新があった場合の処理
} else {
	echo "not changed";
}

凄い単純だけど、これで良いのかな〜

[PHP8.0.3] Fine-Diffによる差分解析

PHP Fine-Diffを使います。
GitHub:PHP-FineDiff

$ git clone https://github.com/gorhill/PHP-FineDiff.git

include 'finediff.php';

$filename1 = 'sample_from.txt';
$from_text = file_get_contents($filename1);

$filename2 = 'sample_to.txt';
$to_text = file_get_contents($filename2);

$opcodes = FineDiff::getDiffOpcodes($from_text, $to_text);

var_dump($opcodes);

$ php index.php
string(534) “c64di:9cd2i2:58c3di:9cdi4:Febrcd4i3:aryc4di:1c17di:uc185i:,c6dc84di:uc120d2i: c122di:uc238di:uc113di:uc528di:bc325di:uc106di:uc36di:uc185di:uc371di:uc267di:uc92di:uc124dc8dc5di:
c335di:uc78di:uc11di3:immcdi4:nselc39di:.ci31:The region visible from Earth (c15d4i4:univc2i3:se)c4d12c4d2i3:herc2i5:with ci15: radius of abouc2d5i2:46cd3c19d8i:,c5i83:based on where the expansion of space has taken the most distant objects observed. c763i:1cdc10d31c36di2:30c14d4i2:3?c3di:3ci:.c4dc474di:uc172di:uc191di:uc166di:uc435di:uc66d34c29di:uc1039”

🤔、ちょっとよくわからんな。

[Bitly API (4.0.0)] PHPで短縮URLを生成する

bitlyにアカウント登録します。
Freeだと1000件/month なので、1日30件が限度。

$long_url = 'https://stackoverflow.com/questions/ask';
$apiv4 = 'https://api-ssl.bitly.com/v4/bitlinks';
$genericAccessToken = '***';

$data = array(
    'long_url' => $long_url
);
$payload = json_encode($data);

$header = array(
    'Authorization: Bearer ' . $genericAccessToken,
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload)
);

$ch = curl_init($apiv4);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
$resultToJson = json_decode($result);

if (isset($resultToJson->link)) {
    echo $resultToJson->link;
}
else {
    echo 'Not found';
}

$ php bitly.php
https://bit.ly/3tp7C1c

OK、全部繋げてみよう

なるほどー

[twitterAPI] botで呟く

$ php composer.phar require abraham/twitteroauth

require 'vendor/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;

$consumerKey = '';
$consumerSecret = '';
$accessToken = '';
$accessTokenSecret = '';

$connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

$result = $connection->post("statuses/update", array("status" => "hello world"));

var_dump($result);

$ php twitter.php

### 画像をPOST

$media1 = $connection->upload('media/upload', array('media' => 'test.jpg'));

//投稿設定
$tweet = [
'status' => $postMsg,  // ツイートの内容(テキスト部分)
'media_ids' => implode(',', [  // 画像の指定
$media1->media_id_string
])
];


//投稿
$result = $connection->post('statuses/update', $tweet);

画像ファイルは、他のサーバーから取得するのではなく、自分のサーバーの画像をuploadしないといけない。
うーん、画像をDLして保存する処理が必要になる。

$file_name = 'tweet.jpg';
$image = file_get_contents($img);
$save_path = 'img/'.$file_name;
file_put_contents($save_path,$image);

こうか↓

後はURL短縮だな。

[beautifulsoup4] aタグの中身を取得

# -*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
from pprint import pprint

URL = 'https://news.yahoo.co.jp/'
with urlopen(URL) as res:
	html = res.read().decode("utf-8")

soup = BeautifulSoup(html, 'html.parser')

titles = soup.select('.sc-esjQYD a')
titles = [t.contents[0] for t in titles]

pprint(titles)

$ python3 title.py
[‘東京で新たに409人の感染確認’,
‘総務相 NTTと会食有無答えず’,
‘変異株 仏で新規感染の7割に’,
‘変異株感染で死亡判明 大阪’,
‘うつぶせ寝で1歳死亡 和解’,
‘ワタミ、労基署から是正勧告’,
‘ワタナベマホト容疑者逮捕’,
‘森本選手「驚いたから」供述’]

で、これを適正開示でやる

$ python3 title.py
[’16:30 36320グリー 特別利益(投資有価証券売却益)の計上(見込み)に関するお知らせ’,
’16:30 37190J-ジェクシード 代表取締役の異動に関するお知らせ’,
’16:30 41740J-アピリッツ 2021年1月期決算短信〔日本基準〕(非連結)’,
’16:30 45990M-ステムリム レダセムチドの慢性肝疾患を対象とした医師主導治験(第2相試験)の第一例目投与に関するお知らせ’,
’16:30 50110ニチレキ 行使価額修正条項付新株予約権の大量行使に関するお知らせ’,
’16:30 67720コスモス電 ‘
// 省略

うーむ、、、cronでメール送信したい。

バッチで走らせる時間にリリースされた開示情報のみ送信したいなー
dateで分岐やな