2017-01-01 1 views
0

Im는 python에 새로운 기능을 추가하고 특정 문자열에 대한 텍스트 파일을 검색하려고 시도한 다음 해당 문자열이 포함 된 전체 라인을 출력합니다. 그러나이 작업을 두 개의 개별 파일로 수행하려고합니다. 주 파일에는 다음 코드가 포함됩니다.파이썬에서 문자열 검색 라인을 출력

def searchNoCase(): 
    f = open('text.txt') 
    for line in f: 
     if searchWord() in f: 
      print(line) 
    else: 
    print("No result") 

    f.close() 



def searchWord(stuff): 
     word=stuff 
    return word 

파일이이 간단한 수정하지만 난 그것을 알아낼 질수 있는지 다음 코드

import main 

def bla(): 
    main.searchWord("he") 

에게 임 포함되어 있습니다. 도움을 크게 평가 될 것입니다

+0

입니다 main.py

def search_file(search_word): # Check we have a string input, otherwise converting to lowercase fails try: search_word = search_word.lower() except AttributeError as e: print(e) # Now break out of the function early and give nothing back return None # If we didn't fail, the function will keep going # Use a context manager (with) to open files. It will close them automatically # once you get out of its block with open('test.txt', 'r') as infile: for line in infile: # Break sentences into words words = line.split() # List comprehention to convert them to lowercase words = [item.lower() for item in words] if search_word in words: return line # If we found the word, we would again have broken out of the function by this point # and returned that line return None 

입니다. 대부분의 경우,'searchNoCase()'를 호출하지 않으므로 파일이 열리지 않습니다. 이 코드는 이제까지 달리는 것에서 확실히 방법이다. – roganjosh

+0

오 예. searchNoCase()를 호출하는 것 외에, 그 밖의 무엇이 없습니까? – Malcommand

+0

음, 1)'searchWord (stuff)'는 절대 아무 것도하지 않습니다 - 당신이 보낸 어떤 값을 되돌려줍니다. 2) 파일 2의 코드는 함수를 호출하지 않기 때문에 실행되지 않습니다. 3)'f에서 searchWord()가 :'왜 파일에서 함수를 찾고 있습니까? 4) 들여 쓰기가'searchNoCase()'에 있습니다. 아직도 더 있습니다. 단일 파일에서 작업을 수행하는 데 집중하는 것이 더 쉬울 것이라고 생각합니다. – roganjosh

답변

0

나는 정확히 __init__.py로 변경된 내용을 확인해야하지만 다음 파일과 같은 디렉토리에 해당 이름의 빈 스크립트를 만듭니다.

독자가 읽을만한 몇 가지 주제를 다뤘습니다. 예를 들어, input (파이썬 3에서)은 항상 문자열을 반환하기 때문에 예외 핸들러는 기본적으로 쓸모가 없다.하지만 걱정해야 할 것이있다.

이이 여기에 코드 근본적인 문제가 있습니다 file1.py

import main 

def ask_for_input(): 
    search_term = input('Pick a word: ') # use 'raw_input' in Python 2 
    check_if_it_exists = main.search_file(search_term) 

    if check_if_it_exists: 
     # If our function didn't return None then this is considered True 
     print(check_if_it_exists) 
    else: 
     print('Word not found') 

ask_for_input() 
+1

우수합니다. 대단히 감사합니다! – Malcommand

관련 문제