简体   繁体   中英

remove everything except lines with % and remove the %

example:

1
Yuumi
78.57%
2075
1956
0.64
62.8
Thresh
77.59%
1079
917
0.83
19.3
Braum
76.00%
1868
1315
1.44
38.0

i want it to be:

78.57
77.59
76.00

(the numbers with the %)

tried looking in forums and use readlines from a file and stuff but im a beginner and couldn't make it work so yea in python, thanks in advance

with open('path/to/the/file') as fd:
    for line in fd:
        if '%' in line:
            print(line.strip().replace('%', ''))

or you can do it in shell:

grep "%" filename | sed 's/%//g' >newfile

You can use regular expressions :

import re

with open("file.txt") as f:
    for line in f:
        r = re.search(r'(\d+(\.[\d]+)?)%', line)
        if r:
            print(r.group(1))

And on your sample data this gives:

78.57
77.59
76.00

regex demo

Let's say you have read all your inputs into a list. You could try this.

inp = ['1', 'Yuumi', '78.59%', ...]
out = [float(a.remove('%')) for a in inp if '%' in a]

You can get all your inputs from a file into a list if you do

with open('my_file.txt') as file:
    inp = file.read.splitlines()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM