2017-10-27 1 views
0

내가 파일 (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. 

을 내가 싶었 파이썬 - 초보자로서 특정 줄의 번호를 얻습니다. 그래서 해결책을 찾고이 게시물을 찾았습니다 : 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"만 출력됩니다.

나는이 게시물 'is' operator behaves differently when comparing strings with spaces을 읽고 내 질문에 대한 답변을 얻길 희망했지만 내 문제에 대한 해답을 적용 할 수 없었습니다.

나는 모든 힌트 나 아이디어를 알고 싶다.

(내가 여러 번. 내가 특정 하나를 필요로하는 파일마다를 반복하고 있지 않다 다른 라인의 인덱스를 액세스 할 필요가 있기 때문 Get Line Number of certain phrase in file Python의 dublicate하지 않습니다.)

+0

가능한 중복을보고 시도 (https://stackoverflow.com/questions/3961265/get-line-number- [파일 파이썬에서 특정 문구의 라인 수를 가져옵니다] of-certain-phrase-in-file-python) –

+0

@sunjazz 예외 인쇄를 시도하십시오. 문제를 디버그하는 데 도움이됩니다. – akhilsp

+0

@akhilsp 그랬지 만 "[06/Oct/2017 : 20 : 18 : 47 +0200] [풀 -2 스레드 7] http://10.12.214.20"은 목록의 요소. 귀하의 답변은 잘 작동합니다! – sunjazz

답변

1

나는 잘못된 목록을 찾고 있다고 생각합니다. 대신 index에서 찾고의의 content

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

이 줄 번호를 얻으려면, 당신은 이것을 시도 할 수 있습니다 :

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)) 
+0

귀하의 솔루션을 사용해 보았지만 여전히 인쇄 중입니다. 나중에이 파일에 루프가 필요하므로 "대상"과 "the_index"를 for 루프에 중첩 시키십시오. content [i.strip ('\ n') for open (testfile)] open (testfile) with f : for f : target = line index = [i의 경우 i는 i를 열거합니다 (내용이 a 인 경우 == 대상)] index = 색인이 없으면 그렇지 않습니다. else index [0] 인쇄 색인 – sunjazz

+0

@sunjazz 편집을 승인했지만 이전 솔루션은 테스트 할 때 저에게 효과적이었습니다. 다른 대상 문자열을 사용 했습니까? – Ajax1234

+0

열거 형의 인수 "start"를 0으로 변경하십시오. –