0

How do you pull data several lines below text you are able to find? That's the short question. More context is below...

I'm learning Python and, as an exercise, I pulled baseball stats from Yahoo Fantasy Baseball to play around with. I coped and pasted the data from the webpage into a text file. It's messy and looks something like this:

Player Note
Charlie Blackmon Col - OF
8:40 pm vs Atl ?
?
Atl
Video Playlist
Video Forecast
Autodraft Hero
115
12
3
99%
159/474
106
27
74
11
.335
?

I was able to set up a simple script to pull out the line with the ballplayers name. See below.

a=open('batters.txt')
for line in a:
    if '-' in line:
        print(line)

However, I'd also like to pull home run totals (ex. 27) and batting average (ex. .335) from the data.

I'd like it to look something like this:

Charlie Blackmon Col - OF, HR: 27, BA: .335

Thanks in advance for your suggestions!

Ian
  • 1
  • 1
  • My suggestion is that you look into Multiline regular expressions. Regular Expressions can be daunting, but they were made for this exact use case - See this question - https://stackoverflow.com/questions/587345/regular-expression-matching-a-multiline-block-of-text – Tim O'Brien Aug 14 '17 at 12:52

1 Answers1

-1

I recommend you to use with statement as it's automatically closes file handler, next read all lines in file to lines list and access it. For example: print(lines[1]) # Charlie Blackmon Col - OF.

You can try this code snippet:

with open('batters.txt') as file:
   lines = file.read().splitlines()
   temp = '%s, HR: %s, BA: %s'
   result = temp % (lines[1], lines[14], lines[17], )
   print(result)
tpszer
  • 53
  • 1
  • 6