[英]For loop in Python and reading input from file
我試圖找出為什么我得到else語句的多個返回結果。 我想從一個文件中讀取。 用戶將輸入一些內容,如果該內容與文件中的單詞或句子/數字匹配,則打印出該行。 如果字的文件中找到它工作正常。 文件內容打印出文檔中匹配的單詞。 但我的問題涉及其他聲明。 如果單詞不在文檔中,則使用else的print語句打印出每一行。 我知道我在for循環中有它,它將迭代文件中所有行的實例。 我的最終目標是打印出一個else語句實例,而不是每一行。
file=open('new_file.txt','r')
new_user=input(str('NEW: '))
for line in file:
line=str(line)
if new_user in line:
print('yes its in here: ',line)
else:
print('Word: ',new_user,' not in here')
file.close()
沒有(else語句)輸出,打印出文檔中找到的正確行:
新:丹尼是的,它在這里:10101他知道他知道嗎? 丹尼
輸出WITH(else):打印出所有不匹配的行。 我只想打印出else塊中聲明的一個實例:
新:伙計
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
一句話:伙計不在這里
使用else語句輸出在文檔中輸入匹配名稱:
新:丹尼
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
字:丹尼不在這里字:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
是的,它在這里:10101他知道他知道嗎? 丹尼
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
一句話:丹尼不在這里
任何正確方向的幫助都會很棒。
謝謝,丹尼
設置標志並在檢查完文件后將其打印出來。
file=open('new_file.txt','r')
new_user=input(str('NEW: '))
flag = False
for line in file:
line=str(line)
if new_user in line:
print('yes its in here: ',line)
flag = True
if not flag:
print('Word: ',new_user,' not in here')
file.close()
另一個選項而不是使用標志是將此邏輯包含在函數中,如果找到該單詞則返回該行,如果從未找到,則返回None
。
def find_word (file, word):
with open(file) as infile:
for line in infile:
if word in line:
return line
return None
new_user=input(str('NEW: '))
ln = find_word('new_file.txt', new_user)
if (ln):
print('yes its in here: ',ln)
else:
print('Word: ',new_user,' not in here')
說明:
通過在找到匹配項后立即返回函數內部,您可以確保它只返回您正在查找的關鍵字的第一個實例。
在切換到使用with open('filename') as ...
語法with open('filename') as ...
,您獲得的優勢是,如果在讀取文件時拋出異常,文件仍將關閉。 它還會在返回之前關閉文件。 您當前使用file=open(...)
文件的方法然后在最后使用file.close()
顯式關閉它意味着在某些情況下文件將無法正確關閉。 (這可能不是問題,但可能在將來)
另一個優點是,將代碼轉換為函數可以使用不同的搜索關鍵字更輕松地多次運行查詢。
你必須像旗子一樣使用,如果你匹配這個詞就會顯示你的東西。 例如:
file=open('new_file.txt','r')
new_user=input(str('NEW: '))
notFound = 1 # The flag that shows if the user was found.
for line in file:
line=str(line)
if new_user in line:
print('yes its in here: ',line)
notFound = 0 # Now is false.
if notFound: # Check if the user wasn't found.
print('Word: ',new_user,' not in here')
file.close()
我認為這應該有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.