필자는 큰 텍스트에서 필요한 수 (범위)를 추출하고이를 float 값으로 변환하는이 솔루션을 제안합니다.
import re
def xNumber(arg): # This method will parse the suffix and return the corresponding multiplier, else 1
switcher = {
"mln": 1000000,
"million": 1000000,
"bln": 1000000000,
"billion": 1000000000,
"thousand": 1000,
"hundred": 100
}
return switcher.get(arg, 1)
rx = re.compile(r'\$(?P<number>\d+(?:,\d{3})?(?:\.\d+)?(?:-\d+(?:,\d{3})?(?:\.\d+)?)?)(?:\s*(?P<suffix>mln|million|bln|billion|thousand|hundred))?')
s = "$3 million, $910,000,$16.5-18 million"
result = ""
for match in rx.finditer(s):
if match.group("suffix") and match.group("number").find("-") == -1: # We have no range and have a suffix
result = str(float(match.group("number"))*xNumber(match.group("suffix")))
elif match.group("number").find("-") > -1: # Range
lst = [float(x) for x in match.group("number").split("-")]
result = str(float(sum(lst))/len(lst)) + (" {}".format(match.group("suffix")) if match.group("suffix") else "")
else: result = float(match.group("number").replace(",","")) # Just return the number found converted to a float
print(result)
는 정규식 r'\$(?P<number>\d+(?:,\d{3})?(?:\.\d+)?(?:-\d+(?:,\d{3})?(?:\.\d+)?)?)(?:\s*(?P<suffix>mln|million|bln|billion|thousand|hundred))?'
인 IDEONE demo
를 참조있다 - $
기호
(?P<number>\d+(?:,\d{3})?(?:\.\d+)?(?:-\d+(?:,\d{3})?(?:\.\d+)?)?)
-
\$
숫자 그룹화 기호 (옵션)로 ,
와 플로트 번호와 선택적 소수 부분 및 선택적 범위
(?:\s*(?P<suffix>mln|million|bln|billion|thousand|hundred))?
- 0 개 이상의 공백 뒤에 대체 "접미사"와 일치합니다.