简体   繁体   中英

How to extract only the first and last numerical value from a txt file, in python?

I have a txt file of this type:

1,23,4,5
4.6,5,7,8.9
2,3,45,21
2,4.2,5,6
58,a,b,c,d
d,e,f,g,h

I want to extract only the first and the last numerical value. in my next program I was able to delete the characters from the string and get a string with the numbers:

import re
with open("C:\testo.txt", "r") as fp:
    lines=fp.readlines()
    for i in range(0, len(lines)):
        x=lines[i]
        result=re.match('\d+', x)
        if result != None:
           valori=result.group()
           print(valori)

my output is:

1
23
4
5
4.6
5
7
8.9
2
3
45
21
2
4.2
5
6
58

now the output I want is :

1 
58

You could use an additional list.

if result != None:
       lst_valori.append(result.group())

Output

>> lst_valori[0]
1
>> lst_valori[-1]
58

in your if result != None: instead of printing the result you could append it to a list

resultList.append(valori)

then you would get the first and last value by slicing the list

for the first item resultList[0]

for the last item resultList[-1]

No need to read the whole file in memory: one row at a time is enough

first = None
last = None
with open("C:\testo.txt") as fp:
    for row in fp:
        for el in row.split(','):
            try:
                n = float(el)
            except ValueError:
                continue
            last = el
            if first is None:
                first = el

print(first, last)

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