|
| 1 | +import tarfile |
| 2 | +import urllib.request |
| 3 | + |
| 4 | +from lindera_py import Segmenter, Tokenizer, build_dictionary, load_dictionary, version |
| 5 | + |
| 6 | + |
| 7 | +def main(): |
| 8 | + # https://Lindera.dev/mecab-ipadic-2.7.0-20070801.tar.gz |
| 9 | + url = "https://lindera.dev/mecab-ipadic-2.7.0-20070801.tar.gz" |
| 10 | + filename = "/tmp/mecab-ipadic-2.7.0-20070801.tar.gz" |
| 11 | + |
| 12 | + # Add User-Agent header to avoid 403 error |
| 13 | + opener = urllib.request.build_opener() |
| 14 | + opener.addheaders = [("User-Agent", f"lindera-py/{version()}")] |
| 15 | + urllib.request.install_opener(opener) |
| 16 | + |
| 17 | + # Download dictionary source file |
| 18 | + urllib.request.urlretrieve(url, filename) |
| 19 | + |
| 20 | + # Extract the dictionary source file |
| 21 | + with tarfile.open(filename, "r:gz") as tar: |
| 22 | + tar.extractall("/tmp/", filter="data") |
| 23 | + |
| 24 | + source_path = "/tmp/mecab-ipadic-2.7.0-20070801" |
| 25 | + destination_path = "/tmp/lindera-ipadic-2.7.0-20070801" |
| 26 | + |
| 27 | + # Build dictionary |
| 28 | + build_dictionary("ipadic", source_path, destination_path) |
| 29 | + |
| 30 | + # Load the built dictionary |
| 31 | + dictionary = load_dictionary(path=destination_path) |
| 32 | + |
| 33 | + # create a segmenter |
| 34 | + segmenter = Segmenter("normal", dictionary) |
| 35 | + |
| 36 | + # create a tokenizer |
| 37 | + tokenizer = Tokenizer(segmenter) |
| 38 | + |
| 39 | + text = "関西国際空港限定トートバッグを東京スカイツリーの最寄り駅であるとうきょうスカイツリー駅で買う" |
| 40 | + print(f"text: {text}\n") |
| 41 | + |
| 42 | + # tokenize the text |
| 43 | + tokens = tokenizer.tokenize(text) |
| 44 | + |
| 45 | + for token in tokens: |
| 46 | + print(token.text) |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + main() |
0 commit comments