(ユーザーからの)時間文字列を秒に変換する関数を作成しようとしています。
私がやりたいのは、ユーザーが次のように時間を文字列として入力できるようにすることです。
"one hour and forty five minutes"
そしてそれを数秒に分解します。したがって、上記の出力は次のようになります。
6300 seconds
ゼロからやりたいのなら、他の答えがいいです。あまり入力せずにできることは次のとおりです。
word2number
このソリューションをインストールする必要があります。
from word2number import w2n
import re
def strTimeToSec(s):
s = s.replace(' and', '')
time = re.split(' hour| hours| minute| minutes| second| seconds', s)[:-1]
if not('hour' in s):
time = ['zero']+time
elif not('minute' in s):
time = [time[0]]+['zero']+[time[1]]
elif not('second' in s):
time = time+['zero']
time = [w2n.word_to_num(x) for x in time]
out = time[0]*3600+time[1]*60+time[2]
return str(out)+' seconds'
>>> print(strTimeToSec('one hour and forty five minute'))
6300 seconds
>>> print(strTimeToSec('one hour forty five minute and thirty three seconds'))
6333 seconds
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加