简体   繁体   中英

Python: Find a string in a text file and print it if the integer in the same line > 1

I need to write a script that checks a file for eeg channel impedance higher than 1 and returns those channel names on the screen. I have no idea how to do this since the channel names also have an integer.

Example of the format of the channel and integer in the text file.

Fp1:          4
Fp2:          1
F7:           0

In my code I created a list of the channels and used semi colons after the eeg channels since its the only thing that defines the channels with impedance values from the rest of the text file.

def read_text(in_file):
    f = open(in_file,'r')
    line = f.readlines()
    f.close()
    channel = ['Fp1:', 'Fp2:', 'F7:', 'F3:', 'Fz:', 'F4:', 'F8:', 'FC5:', 'FC1:', 
          'FC2:', 'FC6:', 'T7:', 'C3:', 'Cz:', 'C4:', 'T8:', 'VEOG:', 'CP5:', 
          'CP1:', 'CP2:', 'CP6:', 'AFz:', 'P7:', 'P3:', 'Pz:', 'P4:', 'P8:', 
          'PO9:', 'O1:', 'Oz:', 'O2:', 'PO10:', 'AF7:', 'AF3:', 'AF4:', 'AF8:', 
          'F5:', 'F1:', 'F2:', 'F6:', 'FT7:', 'FC3:', 'FC4:', 'FT8:', 'C5:', 
          'C1:', 'C2:', 'C6:', 'TP7:', 'CP3:', 'CPz:', 'CP4:', 'TP8:', 'P5:', 
          'P1:', 'P2:', 'P6:', 'PO7:', 'PO3:', 'POz:', 'PO4:', 'PO8:', 'Gnd:', 
          'Ref:']
    for x in channel: 
        ??????


    return()

How does your file separate the entries, is it one entry per line or perhaps comma separated?

If for example you have one entry per line eg

Fp1:          4
Fp2:          0
F7:           10

You could look through the lines and split it by the :

with open(filename, "r") as f:
    for line in f:
        channel, value = line.split(":")  # would create a list ["Fp1", "4"]
        if int(value) > 1:
            print(channel)
            # do something else with channel

>> Fp1
>> F7

In this example it would print both Fp1 and F7 but not Fp2

I don't know if I understood exactly what you want but, if you want to read the line "F1: 4" and, then, store it, you can use dict.

like:

f = open("yourfile.txt")
lines = f.readlines()

data = {}


for line in lines:
    s = line.split()
    data[s[0]] = s[1]

print data

If you want a 'pretty' output, you can do, insted of 'print data':

for key in data.keys():
    print str(key) + " -> " + str(data[key])

Also, if you don't want to display the ':' character, you can change 'line.split()' to 'line.split(":")' and, then, add '.strip()' to 's[1]'.

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