我不使用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()
有許多這裏的代碼根本問題。大多數情況下,你永遠不會嘗試調用searchNoCase(),所以沒有文件打開。儘管如此,這段代碼還是相當不錯的。 – roganjosh
哦,是的。除了調用searchNoCase()之外,還有什麼我失蹤? – Malcommand
好吧,1)'searchWord(stuff)'絕對沒有什麼 - 它可以讓你回到你發送給它的任何值。 2)由於不調用函數,所以文件2中的代碼永遠不會運行。 3)'如果searchWord()在f:'你爲什麼要在文件中尋找一個函數? 4)縮進遍佈在'searchNoCase()'中。還有更多。我認爲你會發現將注意力集中在單個文件中完成任務更容易。 – roganjosh