繁体   English   中英

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

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

所以我有一个.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”已打开,然后使用该数字来找出需要切片的位置以便获取与其关联的数字。

关于您的代码,您尝试两次执行相同的操作。 您正在使用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并显示其类型为float

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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