-4

I have a text file with multiple lines and want to find which lines have values greater than 85%.

'workdata worka worka1 size 84% total'
'workdata workb workb1 size 89% total'
'workdata workc workc1 size 63% total'
'workdata workd workd1 size 94% total'

Can someone please show how I can get just the sentences with 85% or more in the fifth column?

3
  • 6
    Where did you get stuck in your attempt? Aug 9, 2016 at 14:12
  • You'll want to write a regular expression to pull out the number. I'd suggest checking out these resources: regex tutorial, re module.
    – shwoop
    Aug 9, 2016 at 14:15
  • Use a regex (via re module) to extract the digits before the %. convert them to an integer and see if it is greater than 85.
    – martineau
    Aug 9, 2016 at 14:15

2 Answers 2

1

You need to extract percent first, and then filter the lines basing on that.

import re

def extract_percent(line):
    # doing extraction
    try:
        return int(re.findall('[0-9]+%', line)[0][:-1])
    except:
        return 0

print [line for line in lines if extract_percent(line) > 85]

If nothing is found, 0 is returned. Otherwise is returned the number before %. If you have several percent numbers in the string, the first one is returned.

It can become a little bit trickier if the percent can be float, but it is not so hard also. Just play with the regular expression [0-9]+%.

If the position is fixed (fifth column), you can rewrite the extract_percent function this way:

def extract_percent(line):
    try:
        return int(line.split()[4][:-1])
    except:
        return 0
4
  • 1
    You're only encouraging poor question like this...and your indention does not follow PEP 8 - Style Guide for Python Code, so it's not even that great of an example.
    – martineau
    Aug 9, 2016 at 14:20
  • @martineau: Thank you for the tip! Indentation is fixed now. Aug 9, 2016 at 14:22
  • the percent is always in the same position, so the :-1 will work. It is stopping at the first match item, returning 84. I think I may not be reading the file in at the right spot, or not looping through it... Aug 9, 2016 at 14:34
  • @mustang: Using a regular expression is more robust and less likely to break due to small variations in input.
    – martineau
    Aug 9, 2016 at 14:39
0

If you know the percentage will always be in the 5th column, then just split each row on space, remove the percentage sign, and turn it into a float. Something like this:

lines = open("fileName", "r").read().splitlines()
for row in lines:
    if float(row.split()[4].replace("%",""))>85:
        print(row)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.