내가 파일 (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하지 않습니다.)
가능한 중복을보고 시도 (https://stackoverflow.com/questions/3961265/get-line-number- [파일 파이썬에서 특정 문구의 라인 수를 가져옵니다] of-certain-phrase-in-file-python) –
@sunjazz 예외 인쇄를 시도하십시오. 문제를 디버그하는 데 도움이됩니다. – akhilsp
@akhilsp 그랬지 만 "[06/Oct/2017 : 20 : 18 : 47 +0200] [풀 -2 스레드 7] http://10.12.214.20"은 목록의 요소. 귀하의 답변은 잘 작동합니다! – sunjazz