Python源码示例:locale.atof()
示例1
def numberFromString(self, string):
# Uses the current system locale, irrespective of language choice.
# Returns None if the string is not parsable, otherwise an integer or float.
if platform=='darwin':
return self.float_formatter.numberFromString_(string)
else:
try:
return locale.atoi(string)
except:
try:
return locale.atof(string)
except:
return None
# Returns list of preferred language codes in RFC4646 format i.e. "lang[-script][-region]"
# Where lang is a lowercase 2 alpha ISO 639-1 or 3 alpha ISO 639-2 code,
# script is a capitalized 4 alpha ISO 15924 code and region is an uppercase 2 alpha ISO 3166 code
示例2
def float(self, val):
"""
Parse a string to a floating point number. Uses locale.atof(),
in future with ICU present will use icu.NumberFormat.parse().
"""
try:
return locale.atof(val)
except ValueError:
point = locale.localeconv()['decimal_point']
sep = locale.localeconv()['thousands_sep']
try:
if point == ',':
return locale.atof(val.replace(' ', sep).replace('.', sep))
elif point == '.':
return locale.atof(val.replace(' ', sep).replace(',', sep))
else:
return None
except ValueError:
return None
#-------------------------------------------------------------------------
#
# Translations Classes
#
#-------------------------------------------------------------------------
示例3
def _response_hook(self, r: requests.Response, *args, **kwargs):
"""This method always exists as a response hook in order to keep some of the state returned by the
DEP service internally such as:
- The last value of the `X-ADM-Auth-Session` header, which is used on subsequent requests.
- The last value of the `Retry-After` header, which is used to set an instance variable to indicate
when we may make another request.
See Also:
- `Footnote about **X-ADM-Auth-Session** under Response Payload <https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/MobileDeviceManagementProtocolRef/4-Profile_Management/ProfileManagement.html#//apple_ref/doc/uid/TP40017387-CH7-SW2>`_.
"""
if r.status_code == 401: # Token may be expired, or token is invalid
pass # TODO: Need token refresh as decorator
# If the service gives us another session token, that replaces our current token.
if 'X-ADM-Auth-Session' in r.headers:
self._session_token = r.headers['X-ADM-Auth-Session']
# If the service wants to rate limit us, store that information locally.
if 'Retry-After' in r.headers:
after = r.headers['Retry-After']
if re.compile(r"/[0-9]+/").match(after):
d = timedelta(seconds=atof(after))
self._retry_after = datetime.utcnow() + d
else: # HTTP Date
self._retry_after = datetime(*parsedate(after)[:6])
示例4
def is_number(s):
try:
locale.atof(s)
return True
except ValueError:
pass
# put string like '3\/32' into numbers
try:
special_str = '\/'
pos = s.find(special_str)
if pos > 0:
locale.atoi(s[:pos])
locale.atoi(s[pos+len(special_str):])
return True
except ValueError:
pass
return False
示例5
def cast(self, value):
try:
return decimal.Decimal(value)
except:
value = locale.atof(value)
if sys.version_info < (2, 7):
value = str(value)
return decimal.Decimal(value)
示例6
def cast(self, value):
if value in ('', None):
return None
try:
return decimal.Decimal(value)
except:
value = locale.atof(value)
if sys.version_info < (2, 7):
value = str(value)
return decimal.Decimal(value)
示例7
def _test_atof(self, value, out):
self.assertEqual(locale.atof(value), out)
示例8
def cast(self, value):
if value in ('', None):
return None
try:
return decimal.Decimal(value)
except:
value = locale.atof(value)
if sys.version_info < (2, 7):
value = str(value)
return decimal.Decimal(value)
示例9
def parse_real(question, value):
try:
# Use a locale to parse human input since it may have
# e.g. thousands-commas. The locale is set on app
# startup using locale.setlocale in settings.py.
import locale
return locale.atof(value)
except ValueError:
# make a nicer error message
raise ValueError("Invalid input. Must be a number.")
示例10
def _test_atof(self, value, out):
self.assertEqual(locale.atof(value), out)
示例11
def FloatFromString(str_value, use_locale=True):
"""
Converts the given string value into a float, taking in account the current locale.
:param str str_value:
:rtype: float
:returns:
The equivalent float value
:param bool use_locale:
Use locale.atof or standard float conversion (default python output, locale-independent).
:raises ValueError:
If given string is not a valid float literal in the current locale
"""
import locale
if str_value.__class__ != str:
from barril._util.types_ import CheckType
CheckType(str_value, str)
if str_value == PLUS_INFINITY_STR:
return PLUS_INFINITY
elif str_value == MINUS_INFINITY_STR:
return MINUS_INFINITY
elif str_value == NAN_STR:
return NAN
elif use_locale:
return locale.atof(str_value)
else:
return float(str_value)