簡體   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