如何根据索引上可用的字符串获取索引值?

How to get an index value based on a string available on that index?

对于给定的文本文件 (sample.txt),我想根据该行 (index) 上存在的字符串获取索引值。

示例文件包含以下文本 (sample.txt):

line 1: open a file.

line 2: Read a file and store it in a variable.

line 3: check condition using ‘in’ operator for string present in the file or not.

line 4: If the condition true print the index in which the string is found.

line 5: Close a file.

如果我的目标字符串是 'variable'。我想要的输出是: 2

如果我没理解错的话,这可能就是您要找的东西。

def FindLineIndexOfFile(file, text):
    file = open(file, "r")
    line_count = 0
    for lines in file.readlines():
        line_count += 1
        line_index = lines.strip()
        if line_index == text:
            file.close()
            return line_count


index = FindLineIndexOfFile("sample.txt", "hello world")

print(index)

应该这样做:

def indicesOfQueryOnFile(query, file):
    with open(file, 'r') as f:
        cleanLines = [line for line in f.readlines() if len(line.strip()) > 0]
        indices = [i + 1 for i, line in enumerate(cleanLines) if query in line]
    
    return indices

对于文本文件:

line 1: open a file.

line 2: Read a file and store it in a variable.

line 3: check condition using ‘in’ operator for string present in the file or not.

line 4: If the condition true print the index in which the string is found.

line 5: Close a file.

another line with variable

它会输出:

indicesOfQueryOnFile('variable', 'test.txt')
# [2, 6]