繁体   English   中英

如何从用户输入的文本文件中搜索而不是使用 python 打印它?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM