在txt文件中搜索单词并找到相应的行?

时间:2018-07-16 20:45:03

标签: python python-2.7

所以我有一个.txt文件,其中有五列,第一列是字符串,接下来的四列是浮点数。我想做的就是能够在文件中搜索字符串并找到它所在的行,以便可以使用与其关联的浮点数。

在其他线程中,我设法通过将浮点数和字符串放在两个单独的文件中来做到这一点。是否可以将它们放在同一文件中?当我这样做时,出现一个错误,提示我无法将字符串转换为浮点数,反之亦然。

因此,例如,我在文本文件中有此内容:

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

我用于执行此操作的代码与具有两个单独文件时使用的代码相同:

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,]

我得到的错误是:

ValueError: could not convert string to float: blue1

我要获取的是行号“ red1”处于打开状态,然后使用该数字找出需要切片的位置,以便获取与其关联的数字。

1 个答案:

答案 0 :(得分:0)

关于您的代码,您尝试两次执行相同的操作。您正在使用open打开和读取文件,也正在使用np.loadtxt读取文件。错误来自np.loadtxt

对于np.loadtxt,如果文件类型不同,则需要提供文件类型:

文档中有一个示例:

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

对于您来说,看起来就像

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

})

然后您可以使用https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html来找到您的字符串。

您可以将所有内容存储在一个文件中。您只需要以正确的方式读入文件。


使用open进行另一种方式看起来像:

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]))

浮点数现在位于列表中,因此我们可以打印所有浮点数并显示其类型为float

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