- Goal
ChatBotが受信したテキストメッセージと、テキストファイル(CSV)をマッチングさせる。テキストファイルのままで、品番マスタの用に使って参照させる。 - 準備
マスターファイルを作る
テキストファイル menu.csv
UDON001,500
UDON0012,700
SUSHI0123,1200
TONKATSU001,2000
RAMEN10,1000 - How
1. unicodedata を使って、ひらがな・カタカナ・漢字判定と、全角・半角変換する
2. lineでテキストファイルから1行取得して、比較を繰り返す
3. 先頭からで一致したら抜き出すThis file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters# -*- coding: utf-8 -*- import unicodedata inputtext = 'UDON001' # 半角全角混じりでもOK menu = 'menu.csv' # ひらがな・カタカナ・漢字があるかどうかチェック。 あったらTRUE def isJPN(string): for ch in string: name = unicodedata.name(ch) if "CJK UNIFIED" in name \ or "HIRAGANA" in name \ or "KATAKANA" in name: return True return False def main(): if isJPN(inputtext.decode('utf-8')) is False: # 英数字のみなら text = unicodedata.normalize('NFKC', inputtext.decode('utf-8')) # 全角をすべて半角に変更 with open(menu, 'r') as readf: # Menuファイルを開く for line in readf: # 1行づつ if line.find((text.upper() + ',').encode('utf-8')) == 0: # 先頭からテキストが一致して、その直後に','があったら itemname = line[:-1] # その行を取得 print(itemname) if __name__ == '__main__': main() - 結果
(pytest2.7.13) ubuntu@ip-10-0-0-253:~/pytest$ python testmatch.pyUDON001,500 - Thanks!!
以下、参考にさせて頂きました。
http://minus9d.hatenablog.com/entry/2015/07/16/231608
Oracle Application Express Notes | Apps development Notes | Google Cloud Platform | Python | apps test | Cool Beans | English | Books
2017/10/22
テキストファイルをRDBのテーブル(イメージは、品番マスターとか)風に使う - Python
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿