打印包含目标词的文本行
Printing a text line containing the target word
我想在输入所需单词时找到准确的行。例如,如果在一个文本文件中,有 50 行,而 'mirror' 一词位于第 26 行的某处,是否可以打印整行?基本代码写在下面应该可以工作,但没有。
input_text = input("TYPE:")
file = "Library.txt"
with open(file, "r") as txtFile:
for line in txtFile:
if input_text in txtFile.read():
print(line)
else:
print("not found!")
尝试 readlines()
(or directly file descriptor) in combination with enumerate()
获取该行并将其设置为从 1
开始,这样您就可以获得准确的行而不是手动将其递增 1 (enumerate() starts at 0
):
# without readlines()
with open(file, "r") as txtFile:
for line_num, line in enumerate(txtFile, start=1):
if input_text in line:
print(line_num, line)
else:
print("not found!")
# with readlines()
with open(file, "r") as txtFile:
for line_num, line in enumerate(txtFile.readlines(), start=1):
if input_text in line:
print(line_num, line)
else:
print("not found!")
您需要使用 if input_text in line
而不是 if input_text in txtFile.read()
。
如果找到该词,您也可以设置一个标志。如果不是,它将打印“未找到”,如下所示:
with open(file, "r") as txtFile:
found = False
for line in txtFile:
if input_text in line:
print(line)
found = True
if not found:
print("not found!")
input_text = input("TYPE:")
file = "library.txt"
with open(file, "r") as txtFile:
lines = txtFile.readlines()
for line in lines:
if input_text in line:
print(line)
我想在输入所需单词时找到准确的行。例如,如果在一个文本文件中,有 50 行,而 'mirror' 一词位于第 26 行的某处,是否可以打印整行?基本代码写在下面应该可以工作,但没有。
input_text = input("TYPE:")
file = "Library.txt"
with open(file, "r") as txtFile:
for line in txtFile:
if input_text in txtFile.read():
print(line)
else:
print("not found!")
尝试 readlines()
(or directly file descriptor) in combination with enumerate()
获取该行并将其设置为从 1
开始,这样您就可以获得准确的行而不是手动将其递增 1 (enumerate() starts at 0
):
# without readlines()
with open(file, "r") as txtFile:
for line_num, line in enumerate(txtFile, start=1):
if input_text in line:
print(line_num, line)
else:
print("not found!")
# with readlines()
with open(file, "r") as txtFile:
for line_num, line in enumerate(txtFile.readlines(), start=1):
if input_text in line:
print(line_num, line)
else:
print("not found!")
您需要使用 if input_text in line
而不是 if input_text in txtFile.read()
。
如果找到该词,您也可以设置一个标志。如果不是,它将打印“未找到”,如下所示:
with open(file, "r") as txtFile:
found = False
for line in txtFile:
if input_text in line:
print(line)
found = True
if not found:
print("not found!")
input_text = input("TYPE:")
file = "library.txt"
with open(file, "r") as txtFile:
lines = txtFile.readlines()
for line in lines:
if input_text in line:
print(line)