2017-01-01 46 views
0

我是python的新手,我試圖爲一個特定的字符串搜索文本文件,然後輸出包含該字符串的整行。但是,我想將其作爲兩個單獨的文件來完成。主文件包含以下代碼;在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") 

我敢肯定,這是一個簡單的修復,但我似乎無法弄清楚。幫助將不勝感激

+0

有許多這裏的代碼根本問題。大多數情況下,你永遠不會嘗試調用searchNoCase(),所以沒有文件打開。儘管如此,這段代碼還是相當不錯的。 – roganjosh

+0

哦,是的。除了調用searchNoCase()之外,還有什麼我失蹤? – Malcommand

+0

好吧,1)'searchWord(stuff)'絕對沒有什麼 - 它可以讓你回到你發送給它的任何值。 2)由於不調用函數,所以文件2中的代碼永遠不會運行。 3)'如果searchWord()在f:'你爲什麼要在文件中尋找一個函數? 4)縮進遍佈在'searchNoCase()'中。還有更多。我認爲你會發現將注意力集中在單個文件中完成任務更容易。 – roganjosh

回答

0

我不使用Python 3,所以我需要檢查與__init__.py更改的確切內容,但與此同時,在與以下文件相同的目錄中創建一個具有該名稱的空腳本。

我試圖涵蓋幾個不同的主題供您閱讀。例如,異常處理程序在這裏基本沒用,因爲input(在Python 3中)總是返回一個字符串,但它是您不必擔心的。

這是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 

這是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

相關問題