I have this text:
Current Battery Service state: AC powered: true USB powered: false Wireless powered: false Max charging current: 1500000 Max charging voltage: 5000000 Charge counter: 0 status: 2 health: 2 present: true level: 94 scale: 100 voltage: 8146 temperature: 351 technology: Li-ion
and want to create a method to get the value maybe for level or voltage, something like this get_battery_status(property) and pass it “level” and it should return 94 in this case, or pass “temperature” and return 351 on python 3
Advertisement
Answer
You can build a dictionary from the text file, something like:
d ={} with open("text.txt") as f: for l in list(f)[1:]: key, value = l.split(":") d[key.strip()] = value.strip() print(d) def get_battery_status(k): return d[k] print(get_battery_status('level')) print(get_battery_status('Max charging voltage'))
Output:
{'AC powered': 'true', 'USB powered': 'false', 'Wireless powered': 'false', 'Max charging current': '1500000', 'Max charging voltage': '5000000', 'Charge counter': '0', 'status': '2', 'health': '2', 'present': 'true', 'level': '94', 'scale': '100', 'voltage': '8146', 'temperature': '351', 'technology': 'Li-ion'} 94 5000000
Update:
but I have the whole text inside a variable like this…
Based on your comment, you can use:
text = """Current Battery Service state: AC powered: true USB powered: false Wireless powered: false Max charging current: 1500000 Max charging voltage: 5000000 Charge counter: 0 status: 2 health: 2 present: true level: 94 scale: 100 voltage: 8146 temperature: 351 technology: Li-ion""" d = {} for l in [l.strip() for l in text.split("n")[1:]]: key, value = l.split(":") d[key.strip()] = value.strip() print(d) def get_battery_status(k): return d[k] print(get_battery_status('level')) print(get_battery_status('Max charging voltage'))