[英]How to make Python search through a text file and print every matching line?
Apologies for total noob question.对总菜鸟问题表示歉意。 I'm trying to learn Python.
我正在努力学习 Python。 I've searched this site and have not found a solution for me.
我已经搜索了这个网站,但没有找到适合我的解决方案。 Please let me know if one has already been explained.
请让我知道是否已经解释过。
I'm trying to make a search program for a list of movie titles in a .txt
file, and I want it to print every line that contains the words inputted by the user.我正在尝试为
.txt
文件中的电影标题列表制作一个搜索程序,我希望它打印包含用户输入的单词的每一行。
For example, if two of the lines in the text file are例如,如果文本文件中的两行是
22. It Happened One Night (1934)
23. Wonder Woman (2017)
and the user inputs "on" I would like both of these (and any others) to appear, since both contain the "on" at some point.并且用户输入“on”我希望这两个(和任何其他人)都出现,因为它们在某些时候都包含“on”。
I have tried using我试过使用
with open("movies.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if searchphrase in line:
for l in searchlines[i:i+3]: print(l),
print
but this did not work for me.但这对我不起作用。
Something like this maybe:可能是这样的:
with open("movies.txt", "r") as file:
lines = file.read().splitlines()
keyword = "on"
filtered_lines = filter(lambda line: keyword.casefold() in line.casefold(), lines)
for line in filtered_lines:
print(line)
You can refer snippet code bellow您可以参考下面的代码片段
def search(text_search):
with open("movies.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
# if line contains text_search we will print it
if text_search in line:
print(line)
if __name__ == "__main__":
search("One")
def search(text_search):
with open("movies.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if text_search.casefold() in line.casefold():
print(line)
Example call your function with: search("ON")示例调用您的函数: search("ON")
Edited indentation编辑缩进
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.