简体   繁体   English

Python:如何在文本文件中搜索字符串,然后访问其后写的内容

[英]Python: How to search a text file for a string, then access what is written after it

OK, This is probably pretty simple, but I'm still very new to python. 好的,这可能很简单,但是我对python还是很陌生。 I appreciate the help. 感谢您的帮助。

I'm trying to get my program to access a text file indicated from the command line that contains some float data preceded on a line but a related year. 我正在尝试让我的程序访问从命令行指示的文本文件,该文本文件包含一些在行前但相关年份的浮动数据。

For example: 例如:

2010
11 21.5 18 15.2 13 17 14 0 10 16 8.6 5
2013
10.6 14.5 17.9 11.2 1.5 1.9 16 2.2 10 5.2 4.6 5

I want to ask the user to input a year, and then if the year is found in the text file, print the related data for each month. 我想让用户输入年份,然后在文本文件中找到年份,则打印每个月的相关数据。

I can't seem to get this to work. 我似乎无法使它正常工作。

Currently, the program will check for the year, and if it's not found it will say so, and ask again, but if it is found, it will just ask again immediately. 目前,该程序将检查年份,如果找不到,它会说,然后再次询问,但是如果找到,它将立即再次询问。

This is a tidied version of the part of my code: 这是我代码的一部分的整理版本:

f = open(sys.argv[1])

months = ['January', 'February', ...]

while True:
    f.seek(0)
    os.system('cls')
    year = input("Enter year for which you want rainfall data: ")
    line = f.readline().strip()
    while line and line != year:
        line = f.readline().strip()

    if not line:
        print("No rainfall data found for year {}".format(year))
        input("Press Enter to continue ...")
        response = input("Do it again for another year? [[y]/n] ")
        if response == "n":
            break

    else:
        rain_line = f.readline()
        rain_line = rain_line.strip()
        rain_line = rain_line.split()
        rain_strings = list(rain_line)
        rain_numbers = []
        for rain in rain_strings:
            rain_numbers.append(rain)

    print("in {},  {} Millimeters.".format(months[1], rain_numbers[1]))

Anybody see if i'm close or way off? 有人看到我要关闭还是离开?

I've been toying around for hours. 我一直在玩了好几个小时。

Don't consider it one line and the next line, consider them as pairs. 不要将其视为一行,而将其视为下一行。 Using this pairwise iterator : 使用此pairwise迭代器

def parse_rainfall(f):
    for year, data in pairwise(f):
        # ...

For your code, the problem is on the condition of the while expression while line and line != year: . 对于您的代码,问题在于while表达式的条件,而while line and line != year:

If you input like 2010 for year = input("Enter year for which you want rainfall data: ") , it will be parsed to int type, and will never equal to the line , which is a string. 如果为year = input("Enter year for which you want rainfall data: ")输入2010 ,则它将被解析为int类型,并且永远不会等于line ,它是一个字符串。 Use a conversion str(year) will fix the problem. 使用转换str(year)将解决此问题。

But you may want to use a different method both for efficiency and coding. 但是您可能想使用其他方法来提高效率和编码。

If the file is not very large, try to parse the file first, making it into a Python dictionary like {2010: [11 21.5 18 15.2 13 17 14 0 10 16 8.6 5], ...} , then you can just query the dictionary by using the year as key and fetch its data. 如果文件不是很大,请尝试首先解析文件,然后将其放入Python字典中,例如{2010: [11 21.5 18 15.2 13 17 14 0 10 16 8.6 5], ...} ,然后可以查询使用年份作为关键字并获取其数据的字典。

If the file is large, consider to parse and write it to a database, either SQL or NoSQL, then the query becomes as simple as a using Python dictionary. 如果文件很大,请考虑解析并将其写入SQL或NoSQL数据库,然后查询变得像使用Python字典一样简单。

Otherwise, you can change how you used to search in your text file and use a solution like this (I didn't test it with a large file. Please let me know if it breaks with it). 否则,您可以更改以前在文本文件中进行搜索的方式,并使用类似的解决方案(我没有对大型文件进行过测试。如果它不兼容,请告诉我)。

I'm assuming your input file is called input_file : 我假设您的输入文件称为input_file

def get_data():
    data = list(k.rstrip() for k in open("input_file", 'r'))
    d = list(data[k:k+2] for k in range(0,len(data),2))
    final = []
    while True:
        user_data = input("Enter a year: ")
        if user_data == 'q':
            break
        for k in d:
            if k[0] == user_data:
                final.append(k[1])

        if final != '':
            print("\n".join(final))
            final = []
        else:
            print("Cannot find any data for the year:", user_data)


get_data()

Demo: 演示:

Enter a year: 2010
11 21.5 18 15.2 13 17 14 0 10 16 8.6 5
Enter a year: 2013
10.6 14.5 17.9 11.2 1.5 1.9 16 2.2 10 5.2 4.6 5
Enter a year: 2000
Cannot find any data for the year: 2000
Enter a year: 2010
11 21.5 18 15.2 13 17 14 0 10 16 8.6 5
Enter a year: 2100
Cannot find any data for the year: 2100
Enter a year: 22
Cannot find any data for the year: 22
Enter a year: q

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何打开文本文件并查找在一行中的特定单词和 append 文件名之后写入的内容到 Python 中的列表 - How to open a text file and find what is written after a specific word in a line and append that files name to a list in Python 在 python 中的特定字符串之后搜索文本文件中的字符串 - search a string in a text file after a particular string in python 从Django / Python更改网站的哪个部分,以在搜索栏中获得预写的文本? - What part of the website from Django/ Python to change to get a pre-written text in search bar? Python:搜索字符串,在该字符串之后解析文本,然后添加到列表中 - Python: Search for a string, parse text after that string, add to a list 如何用Python中写入文件的字符串构建Numpy数组 - How to build Numpy array from a String written in file in Python 在字符串python中搜索文本 - Search text in string python 如何在目录中的所有文本文件中搜索字符串并将找到的结果放在 Python 的文本文件中 - How do I search all text files in directory for a string and place the found result in a text file in Python 如何使用python在可执行输出中搜索文本字符串? - How to search for text string in executable output with python? Python 2:在从包含该字符串的文本文件返回整行之前,如何在文本文件中搜索字符串? - Python 2: How do I search for a string in a text file before returning the entire line from the text file that contains this string? 使用python在字符串之后将文本文件插入另一个文本文件? - insert a text file into another text file after a string using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM