![](/img/trans.png)
[英]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.