[英]How to search for word in text file and print the entire line with Python?
[英]How to open a file in python, search for a word ignoring case, print success of word is found?
您正在閱讀一位陌生作者的書,並對它們可能來自哪個國家感到好奇。 您決定編寫一個程序來幫助您根據書中單詞的拼寫進行猜測。
編寫一個程序,讀取一個單詞(例如顏色或顏色),並檢查它是否出現在book.txt文件中,並在書中找到打印輸出。 或在書中找不到。
例如,給定book.txt文件:
假設? 當她什至不知道其余數據是什么樣時,她將如何形成假設?
問題是,無論我嘗試了什么,我都無法使我的代碼忽略單詞的大小寫。 提供的輸入單詞將始終為小寫字母,但您的程序應以不區分大小寫的方式進行匹配。
我的代碼:
word = input("Word to look for: ")
with open('book.txt') as f:
if word in f:
print(word,"was found in the book.")
else:
print(word,"was not found in the book.")
預期產量:
Word to look for: hypothesize hypothesize was found in the book.
請保持盡可能簡單。 我仍在通過不允許導入未內置模塊的在線程序進行學習。
您可以嘗試:
word = input("Word to look for: ")
word_lower = word.lower()
with open('book.txt', 'r') as fh:
data = fh.read().lower()
if word_lower in data:
print(word,"was found in the book.")
else:
print(word,"was not found in the book.")
我只是將word
和data
(文件的內容)都強制轉換為小寫.lower()
,使其變成不區分大小寫的形式。
我沒有直接更新word
,而是將降低的字符串存儲在另一個變量( word_lower
)中,以允許您准確打印用戶輸入的內容。
您可以遍歷文件中的單詞,並以小寫形式進行比較:
wordToMatch = input("Word to look for: ")
with open('book.txt') as f:
for line in f:
for word in line.split() :
if word.lower() in wordToMatch :
print(word,"was found in the book.")
else:
print(word,"was not found in the book.")
實際上,要強制將變量中的值轉換為小寫,您不必定義新變量,只需使用舊變量並進行更改即可。 因此,代替word_lower = word.lower()
只需執行word = word.lower()
或直接將word.lower()
放入if語句即可。 這樣會更有效率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.