获取包含 python 中非字母数字元素的列表中非字母数字字符串的索引

Get the index of a non-alphanumeric-string in a list containing non-alphanumeric elements in python

我有一个这样的文件 (test.txt):

[06/Oct/2017:20:18:47 +0200] [pool-2-thread-7] http://10.12.214.20
[06/Oct/2017:20:19:38 +0200] [pool-2-thread-4] http://10.12.214.18
[06/Oct/2017:20:19:38 +0200] [pool-2-thread-4] http://10.12.214.18
[06/Oct/2017:20:19:49 +0200] [pool-2-thread-8] http://10.12.214.18
[06/Oct/2017:20:19:59 +0200] [pool-2-thread-7] ends.
[06/Oct/2017:20:20:47 +0200] [pool-2-thread-7] http://10.12.214.20
[06/Oct/2017:20:21:24 +0200] [pool-2-thread-4] ends.
[06/Oct/2017:20:21:34 +0200] [pool-2-thread-8] ends.

作为一个 python-初学者,我想获取特定行的行号,所以我搜索了一个解决方案并找到了这个 post: Finding the index of an item given a list containing it in Python。 我正在使用@tanzil 的答案,因为稍后我可能会查找不在列表中的元素。

我就是这样做的:

将原始文件的行保存在列表中:

with open(test.txt) as f:
    content = [line.rstrip('\n') for line in f]
    print len(content)
index = [x for x in range(len(content))]

遍历原始文件:

with open(test.txt, "r") as file:
    for line in file:
        print find_element_in_list(index, line.rstrip('\n'))

求原文件每一行的索引:

def find_element_in_list(index_list, list_element):
    try:
        index_element = index_list.index(list_element)
        return index_element
    except ValueError:
        return None

结果,完全没有匹配。 我只得到 "None" 作为输出。

我读了这个 post 'is' operator behaves differently when comparing strings with spaces 并希望得到我的问题的答案,但无法根据我的问题调整答案。

如果有任何提示或想法,我将不胜感激!

(这不是 Get Line Number of certain phrase in file Python 的副本,因为我需要多次访问不同行的索引。我不会在每次需要特定文件时都遍历文件。)

要获取行号,你可以试试这个:

file = open('filename.txt')
data = file.readlines()
target = "[06/Oct/2017:20:19:49 +0200] [pool-2-thread-8] http://10.12.214.18"
for i, item in enumerate(data, start=1):
    if item == target:
        print('Target is in line: ', str(i))

我认为您查错了列表。不要查看 index,而是尝试查看 content

with open('test.txt', "r") as file:
    for line in file:
        print find_element_in_list(content, line.rstrip('\n'))