To retrieve the values from the JSON file, I use this code:
import json
json_file = json.load(open('Bla_Bla_Bla.json'))
master_data = json_file['messages']
for unique_message in master_data:
print(unique_message['text'])
This is the JSON template:
{
"name": "Bla Bla Bla",
"type": "public_channel",
"id": 123456789,
"messages": [
{
"id": 12460,
"type": "message",
"date": "2022-02-07T04:14:51",
"from": "Bla Bla Bla",
"from_id": "channel1127646148",
"text": "Yesterday's Tips\n \n First Half\n Tips: 2\n Win/Loss: 0/2\n Void: 0\n Win Ratio: 0%\n Invested: 2u\n Net Profit: -2u\n ROI: -100%\n \n Second Half\n Tips: 10\n Win/Loss: 4/4\n Void: 2\n Win Ratio: 40%\n Invested: 8u\n Net Profit: 1.145u\n ROI: 14.3%\n \n Total\n Tips: 12\n Win/Loss: 4/6\n Void: 2\n Win Ratio: 33.3%\n Invested: 10u\n Net Profit: -0.855u\n ROI: -8.6%\n \n Highest Odds won: 2.500"
}
]
}
This is the output text:
Yesterday's Tips
First Half
Tips: 2
Win/Loss: 0/2
Void: 0
Win Ratio: 0%
Invested: 2u
Net Profit: -2u
ROI: -100%
Second Half
Tips: 10
Win/Loss: 4/4
Void: 2
Win Ratio: 40%
Invested: 8u
Net Profit: 1.145u
ROI: 14.3%
Total
Tips: 12
Win/Loss: 4/6
Void: 2
Win Ratio: 33.3%
Invested: 10u
Net Profit: -0.855u
ROI: -8.6%
Highest Odds won: 2.500
I'm trying to collect the value to Net Profit:
that is inserted inside Total
, the texts can change and the positions too, but whenever there is a Total
, there will be a Net Profit:
.
The value I want to collect in this case is:
-0.855u
How can I go about getting that specific part of the text value?
CodePudding user response:
For more complex cases, you may want to look into Regular Expressions (Regex), but for this simple case:
string = unique_message["text"] # the json data
string = string[string.find("Total"):] # cut all the part before "Total"
string = string[string.find("Net Profit") 12:] # cut all the part before "Net Profit" (the 12 removes the Net Profit bit too)
string = string[:string.find("\n")] # take the part of the string till the next line
print(string)
Here, we use the str.find()
function which returns the index of a certain part of a string together with string slicing string[start:end]
to find only the part of the string needed. The \n
is a special character which denotes the end of a line.
CodePudding user response:
If the Net Profit: -0.855u
is always after the Total
, you can first find the index of Total
and then use that to further narrow down your search scope and look for Net Profit
.
# Your other logics
text = unique_message['text']
try:
i = text.index("Total")
profit_beginning = text[i:].index("Net Profit:")
except ValueError:
# Don't look for profit
pass
You can further enhance the lookup by using a RegEx and catch the number only.