Skip to content
Advertisement

How to collect a specific value from a text that is always a few lines below another text value?

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 Tipsn   n   First Halfn   Tips: 2n   Win/Loss: 0/2n   Void: 0n   Win Ratio: 0%n   Invested: 2un   Net Profit: -2un   ROI: -100%n   n   Second Halfn   Tips: 10n   Win/Loss: 4/4n   Void: 2n   Win Ratio: 40%n   Invested: 8un   Net Profit: 1.145un   ROI: 14.3%n   n   Totaln   Tips: 12n   Win/Loss: 4/6n   Void: 2n   Win Ratio: 33.3%n   Invested: 10un   Net Profit: -0.855un   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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement