0

文字列(XMLフィードから抽出)を含む変数があります。文字列値は、整数、日付、または文字列のタイプにすることができます。文字列から指定されたデータ型に変換する必要があります。私はこのようにやっていますが、少し醜いので、もっと良いテクニックがあるかどうか尋ねています。より多くのタイプをチェックする場合は、ブロックを除いて、非常にネストされたtryで終了します。

def normalize_availability(self, value):
    """
    Normalize the availability date.
    """
    try:
        val = int(value)
    except ValueError:
        try:
            val = datetime.datetime.strptime(value, '%Y-%m-%d')
        except (ValueError, TypeError):
            # Here could be another try - except block if more types needed
            val = value

ありがとう!

4

3 に答える 3

5

便利なヘルパー機能を使用してください。

def tryconvert(value, default, *types):
    """Converts value to one of the given types.  The first type that succeeds is
       used, so the types should be specified from most-picky to least-picky (e.g.
       int before float).  The default is returned if all types fail to convert
       the value.  The types needn't actually be types (any callable that takes a
       single argument and returns a value will work)."""
    value = value.strip()
    for t in types:
        try:
            return t(value)
        except (ValueError, TypeError):
            pass
    return default

次に、日付/時刻を解析するための関数を記述します。

def parsedatetime(value, format="%Y-%m-%d")
    return datetime.datetime.striptime(value, format)

今、それらをまとめます:

value = tryconvert(value, None, parsedatetime, int)
于 2013-02-04T15:53:17.057 に答える
0
def normalize_availability(value):
    """
    Normalize the availability date.
    """
    val = value
    try:
        val = datetime.datetime.strptime(value, '%Y-%m-%d')
    except (ValueError):
        if value.strip(" -+").isdigit():
            val = int(value)

    return val
于 2013-02-04T15:49:16.707 に答える
0

正しい方法は、xmlからそれぞれのタイプを知ることです。これにより、たまたま数値文字列がintなどになるのを防ぐことができます。しかし、それが不可能であると仮定します。

私が好むint型の場合

if value.isdigit():
    val = int(value)

日付については、私が考えることができる他の唯一の方法は、それを分割してパーツを確認することです。これは、より厄介で、strptimeに例外を発生させるだけです。

于 2013-02-04T15:42:38.043 に答える