[英]How to search within a text file from a users input than print it using python?
我在嘗試使用 python 讀取文本文件中的多行時遇到問題。 我的問題是,獲取用戶特定的輸入並找到那段文本並將其打印出來,並在其后加上多行。 我試圖通過使用elif
繼續這部分來在一段while
內保持這一點 function 。 This code is to take a users US State that was inputted and print that state following with the capitol of that state and state bird. 這是通過讀入一個包含所有 50 個州信息的文本文件來完成的。 這是我目前正在使用的代碼。 這是我正在處理的菜單的一小部分。
elif x == "2":
f = open("States and Capitals.txt", "r")
x = input("Enter the state you would like to search: ")
searchlines = f.read()
for x, line in enumerate(searchlines):
if x in line:
for l in searchlines[i:i+3]: print l,
print(x)
f.close()
文本文件示例:
阿拉巴馬州
首都:蒙哥馬利
State 鳥:黃錘
State 花:山茶花
阿拉斯加州
首都:朱諾
State 鳥:柳雷鳥
State 花:勿忘我
亞利桑那
首都:鳳凰城
State 鳥:仙人掌鷦鷯
State 花:仙人掌仙人掌花
您可以使用此代碼
f = open("States and Capitals.txt", "r")
x = input("enter value to search : ")
searchlines = f.read()
if(searchlines.find(x)):
print(x)
f.close()
我認為這樣的事情可能會奏效。 這樣做的結果是您將獲得包含所需行的變量 output。 然后你可以打印它。
elif x == "2":
state= input("\nPlease enter a State.\n")
with open("States and Capitals.txt", "r") as f:
for line in f:
if state.lower() in line.lower(): output=line
嘗試這個。 您可以首先使用split()
function 將文件輸入拆分為列表,在這種情況下使用"\n"
或newline
作為分隔符。 然后,您只需從索引或找到的字符串(如果存在)中打印接下來的 3 行。 在這里,我假設您要打印 state、首都、鳥和花(共 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()
如果您想從 output 中排除 State 因為它可能是多余的,那么您可以進行以下小改動:
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()
這是一次讀取文件三行並從 state 中找到匹配(如果有)的數據的一種方法:
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, 3, ''): # 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}')
樣品 output:
State: Kansas, Bird: Western Meadowlark
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.