2017-01-01 5 views
0

ImはPythonに新しいので、特定の文字列のテキストファイルを検索しようとすると、その文字列を含む行全体が出力されます。しかし、私はこれを2つの別々のファイルとして実行したい。メインファイルには次のコードが含まれています。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 

ファイル2は、これは簡単な修正ですが、私はそれを把握するように見えるカント次のコード

import main 

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

Imは必ず含まれています。

+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

私はPython 3を使用しないため、__init__.pyで変更された内容を正確に確認する必要がありますが、その間に次のファイルと同じディレクトリにその名前の空のスクリプトを作成してください。

私はいくつかの話題を読んだことがあります。たとえば、input(Python 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

関連する問題