简体   繁体   中英

Searching a txt file for a word and finding the corresponding row?

So I have a .txt file that has five columns, the first is a string and the next four are floats. What I want to do is be able to search the file for the string and find the row which it is on so I can use the floats associated with it.

From other threads I've managed to do this by putting the floats and strings in two separate files. Is it possible to have them in the same file? When I do this, I get an error about being unable to convert a string to a float or vice versa.

So for example, I have this in the text file:

blue1 0 1 2 3
blue2 4 5 6 7
red1 8 9 10 11
red2 12 13 14 15 

The code I am using to do this is the same code I used when I had two separate files:

lookup = 'red1'
with open(file) as myFile:
for row, line in enumerate(myFile, 1):
    if lookup in line:
        print 'found in line:', row

data = np.loadtxt(path + file)
d = data[:row,]

The error I am getting says:

ValueError: could not convert string to float: blue1

What I'm trying to get is the row number "red1" is on, then use that number to figure out where I need to slice in order to get the numbers associated with it.

Regarding your code, you are trying to do the same thing twice. You are using open to open and read the file and also np.loadtxt to read it. The error is from the np.loadtxt .

For np.loadtxt you need to supply the file types if they aren't all the same:

There is an example in the docs:

np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
                      'formats': ('S1', 'i4', 'f4')})

For yours, it'd look like

data = np.loadtxt('text.txt', dtype={
    'names' : ('color', 'a', 'b', 'c', 'd'),
    'formats' : ('U50', 'f', 'f','f', 'f')

})

And then you can use https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html to locate your string.

You can store everything in one file. You just need to read in the file in the correct manner.


Doing it the other way with open would look like:

with open('text.txt') as f:
    for line in f:
        my_arr = line.split()
        my_str = my_arr.pop(0) # Create a list of all the items and then pop the string off the list
        my_arr = list(map(float, my_arr))
        if my_str == "blue1":
            print(my_arr, type(my_arr[0]))

The floats are now in a list so we can print all of them and show that their type is float

Output: ([0.0, 1.0, 2.0, 3.0], <type 'float'>)

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