0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

外貨を全角の日本円にして返すコードを書いた

Last updated at Posted at 2019-05-20

グーグル検索でよくない?

いちいち新しいタグを開いて入力するのがめんどくさい。また、39億6487万ドルとかごちゃごちゃした数字になると、「変換」の文字を含めないと円換算してくれないのが忙しい業務中はリズムが崩れて腹立たしいことこの上ありません。

出来たもの

日本語だけでなく、外国語も対応(グーグル翻訳)です。日本語で書かれた元の通貨とその額、円換算した額、換算レートを参照した時間を返します。ただし、1万ないし1千以下の数値は普段必要ないため、細かい金額が重要な場合は使えません。また、対応通貨はとりあえずよく遭遇するドル、ユーロ、元、ルーブル、ポンドです。コードは最下部ないしGithubにあります。

$500 million
('5億ドル', '約549億7526万1132円', ['05月21日 00:00 更新'])

350,9 миллиарда рублей
('3509億ルーブル', '約5982億9599万274円', ['05月21日 00:00 更新'])

必要なモジュール

インストール
pip install mojimoji
pip install googletrans

コード全文

コード全文
import requests
import lxml.html
import re
import mojimoji
from googletrans import Translator


def fcur(currency, tril=0, bil=0, mil=0, thous=0):
  """
  Convert forreign currency to full_width japanese yen
  """
  
  translator = Translator()
  currency = translator.translate(currency, dest='ja').text # translate to ja
  translated = mojimoji.han_to_zen(currency)
  
  currency = re.sub(r'ドル', ' USD', currency) # replace with currency code
  currency = re.sub(r'ルーブル', ' RUB', currency)
  currency = re.sub(r'', ' CNY', currency)
  currency = re.sub(r'ポンド', ' GBP', currency)
  currency = re.sub(r'ユーロ', ' EUR', currency) 
  currency = re.sub(r',', '', currency) # get rid of commma
  
  cur_name = currency.split()[-1] # get currency name
  if '' in currency: # convert to number, multiplying by powers of 10
    tril = int(re.findall(r'\d{1,4}(?=兆)', currency)[0]) * (10 ** 12)
  if '' in currency:
    bil = int(re.findall(r'\d{1,4}(?=億)', currency)[0]) * (10 ** 8) 
  if '' in currency:
    mil = int(re.findall(r'\d{1,4}(?=万)', currency)[0]) * (10 ** 4)
  if '' in currency:
    thous = int(re.findall(r'\d(?=千)', currency)[0]) * (10 ** 3)
  ammount = tril + bil + mil + thous 
  
  url = 'https://keisanki.me/calculator/index/{}/{}'.format(cur_name, ammount)
  response = requests.get(url)
  content = lxml.html.fromstring(response.content)
  yen = content.xpath('/html/body/section[1]/div/div/div[1]/h1/span/text()')[0]
  date  = content.xpath('/html/body/section[1]/div/div/div[1]/h3/text()')
  # retrieve date to check whether currency data are actuall
  
  table = str.maketrans('','',',') # get rid of comma
  yen = yen.translate(table)
  yen_fullwidth = mojimoji.han_to_zen(yen) # convert to fullwidth
  return translated, yen_fullwidth, date

fcur(input())
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?