您可以使用此代码
f = open("States and Capitals.txt","r")
x = input("enter value to search : ")
searchlines = f.read()
if(searchlines.find(x)):
print(x)
f.close()
,
我认为类似的方法可能有效。这样的结果是您将获得具有所需行的变量输出。然后可以打印出来。
rem
,
尝试一下。您可以先使用split()
函数将文件输入拆分为一个列表,该函数在本例中使用"\n"
或newline
作为分隔符。然后,您只需从索引或找到的字符串(如果存在)中打印接下来的3行。在这里,我假设您要打印州,首府,鸟和花(总共4行)。
elif x == "2":
f = open("States and Capitals.txt","r")
x = input("Enter the state you would like to search: ")
searchlines = f.read().split("\n")
if x in searchlines:
index = searchlines.index(x)
for i in range(4):
print(searchlines[index+i])
f.close()
如果您想从输出中排除状态,因为它可能是多余的,则可以进行以下较小更改:
elif x == "2":
f = open("States and Capitals.txt","r")
x = input("Enter the state you would like to search: ")
searchlines = f.read().split("\n")
if x in searchlines:
index = searchlines.index(x)
for i in range(1,4):
print(searchlines[index+i])
f.close()
,
这是一种同时读取文件三行并从其发现匹配的状态(如果有)打印数据的方法:
from itertools import zip_longest
# See https://docs.python.org/3/library/itertools.html#itertools-recipes
def grouper(iterable,n,fillvalue=None):
''' Collect data into fixed-length chunks or blocks. '''
# grouper('ABCDEFG',3,'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args,fillvalue=fillvalue)
target_state = input('Please enter a state name: ')
with open('States and Capitals.txt','r') as file:
for group in grouper(file,''): # Read file three lines at a time.
state,capital,bird = map(str.rstrip,group) # Remove newlines.
if state == target_state:
print(f'State: {state},Bird: {bird}')
break # All done.
else:
print(f'Error: No state found named {target_state}')
示例输出:
State: Kansas,Bird: Western Meadowlark
本文链接:https://www.f2er.com/3157615.html