精通正则表达式中,有一个温度转换程序,使用perl写的,现在转换成python来写,也算是对re的一个应用:

#!/usr/bin/env python
#-*- coding: utf-8 -*-
#filename:temperature_exchange.py

import re


def Match():
    imply = raw_input("Type you temperature(e.g:32F,100C): ")
    re_str = r'([-+]?[0-9]+(\.[0-9]*)?)\s*([CF])$'
    match = re.match(re_str,imply,re.I)
    if match:
        num = re.search(re_str,imply,re.I).group(1)
        kind = re.search(re_str,imply,re.I).group(3)
        if(kind == 'c' or kind == 'C'):     
            c = float(num)
            f = (c * 9 / 5) + 32
        else:
            f = float(num)
            c = (f - 32) * 5 / 9
        print "%.2fC is equal to %.2fF \n" % (c,f)
    else:
        print "\nExpecting a number followed by C or F "
        print "sorry,your type style is out of the regular!\n"

while True:
    Match()
运行测试情况如下:
>>> ================================ RESTART ================================
>>> 
Type you temperature(e.g:32F,100C): 23f
-5.00C is equal to 23.00F 

Type you temperature(e.g:32F,100C): 45F
7.22C is equal to 45.00F 

Type you temperature(e.g:32F,100C): 34c
34.00C is equal to 93.20F 

Type you temperature(e.g:32F,100C): 23C
23.00C is equal to 73.40F 

Type you temperature(e.g:32F,100C): 23

Expecting a number followed by C or F 
sorry,your type style is out of the regular!

Type you temperature(e.g:32F,100C): 23.4

Expecting a number followed by C or F 
sorry,your type style is out of the regular!

Type you temperature(e.g:32F,100C): 23.45F]

Expecting a number followed by C or F 
sorry,your type style is out of the regular!

Type you temperature(e.g:32F,100C): 23.45F
-4.75C is equal to 23.45F 

Type you temperature(e.g:32F,100C): -23

Expecting a number followed by C or F 
sorry,your type style is out of the regular!

Type you temperature(e.g:32F,100C): -23F
-30.56C is equal to -23.00F 

Type you temperature(e.g:32F,100C): -23C
-23.00C is equal to -9.40F 

Type you temperature(e.g:32F,100C): +45F
7.22C is equal to 45.00F 

Type you temperature(e.g:32F,100C): +34.45f
1.36C is equal to 34.45F 


posted on 2022-07-05 18:12  我在全球村  阅读(12)  评论(0编辑  收藏  举报