LoginSignup
5
0

More than 5 years have passed since last update.

bibファイルの日本語文献(2バイト文字)を判定してフラグを建てるPythonプログラム

Posted at

背景

この記事の続きです。
bibファイルのうち,日本語文献と思しきものに,isjapanese = {true}という行を自動で追加するPythonプログラムになります。

基本的な流れ

bibファイルの中身は基本的に@で区切られているのでsplitで分解できます。

  • @の文字で文章をsplit
  • ブロックごとに2バイト文字が存在するか判定
  • 日本語判定を受けたブロックの後ろを置換
  • @をつけ直して再構成,ファイルに書き込み

という流れをとりました。

Pythonによる2バイト文字判定

こちらの方の記事を参考にしました。
https://minus9d.hatenablog.com/entry/2015/07/16/231608

#https://minus9d.hatenablog.com/entry/2015/07/16/231608
import unicodedata
def is_japanese(string):
    for ch in string:
        name = unicodedata.name(ch,'Undefined') 
        if "CJK UNIFIED" in name \
        or "HIRAGANA" in name \
        or "KATAKANA" in name:
            return True
    return False

元記事からの変更点としてunicodedata.nameに改行コードを入れるとErrorを吐くのでデフォルト値として'Undefined'を設定しています。
リファレンスがわかりやすくて助かった…
https://docs.python.jp/3/library/unicodedata.html

その他仕様

python addJPflag.py <元ファイル>.bib

とうつと

<元ファイル>_withJPflag.bib
という名前でフラグ付きのファイルを作成するようにしました。

ソースコード

結構簡単な仕様でしたので割とすぐできました。
退屈なことはPythonにやらせろってはっきりわかんだね。

import unicodedata
import sys

def is_japanese(string):
    for ch in string:
        name = unicodedata.name(ch,'Undefined') 
        if "CJK UNIFIED" in name \
        or "HIRAGANA" in name \
        or "KATAKANA" in name:
            return True
    return False


if __name__ == "__main__":
    argv = sys.argv

    if len(sys.argv)==1:
        print('Please parse .bib file name!')
        exit(-1)

    # 1. read file
    fname = argv[1]
    f = open(fname,encoding="utf-8")
    data = f.read()
    # 2. split file
    sdata = data.split('@')
    # 3. add string
    output = ''
    for strings in sdata:
        if is_japanese(strings):
            output = output +'@' + strings[:-3] + ',\n isjapanese = {true}\n}\n'
        else:
            output = output +'@'+ strings
    output_bib = output[1:]
    # 4. save as new files
    fname_o = fname.replace('.bib','_withJPflag.bib')
    with open(fname_o,'w',encoding='utf-8') as fo:
        fo.write(output_bib)
5
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0