Created
June 1, 2020 09:46
-
-
Save seanwiseman/d2f40f7ea522f2cb2308077d6ab05537 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def extract_key_value_pairs(input_str, keys): | |
| """ | |
| # Example: | |
| result = extract_key_value_pairs( | |
| input_str="Postcode: NG11 Radius: 5 Price range: 450000-500000 Number of bedrooms: 2", | |
| keys=["Postcode", "Radius", "Price range", "Number of bedrooms"] | |
| ) | |
| >>> result | |
| {'Number of bedrooms': '2', 'Radius': '5', 'Postcode': 'NG11', 'Price range': '450000-500000'} | |
| """ | |
| data = {} | |
| for k in keys: | |
| value = "" | |
| char_index = input_str.find(k) + len(k) + 2 | |
| while True: | |
| try: | |
| char = input_str[char_index] | |
| except IndexError: | |
| break | |
| if char == " ": | |
| break | |
| value += char | |
| char_index += 1 | |
| data[k] = value | |
| return data | |
| result = extract_key_value_pairs( | |
| input_str="Postcode: NG11 Radius: 5 Price range: 450000-500000 Number of bedrooms: 2", | |
| keys=["Postcode", "Radius", "Price range", "Number of bedrooms"] | |
| ) | |
| print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment