【问题标题】:Python: Search particular string in filePython:在文件中搜索特定字符串
【发布时间】:2017-01-09 08:00:26
【问题描述】:

我有文本文件,以以下格式存储订单信息。我尝试按块的第一行搜索订单,代表 ID 并打印下 7 行。但是我的代码只检查第一行或打印所有包含输入数字的行。有人可以帮帮我吗?

4735
['Total price: ', 1425.0]
['Type of menu: ', 'BBQ']
['Type of service: ', '     ']
['Amount of customers: ', 25.0]
['Discount: ', '5%', '= RM', 75.0]
['Time: ', '2017-01-08 21:39:19']

3647
['Total price: ', 2000.0]
['Type of menu: ', ' ']
['Type of service: ', 'Tent    ']
['Amount of customers: ', 0]
    .......

我使用以下代码在文本文件中进行搜索。

        try:
            f = open('Bills.txt', 'r')
            f.close()
        except IOError:
            absent_input = (raw_input("|----File was not founded----|\n|----Press 'Enter' to continue...----|\n"))
            report_module = ReportModule()
            report_module.show_report()
        Id_input = (raw_input("Enter ID of order\n"))
        with open("Bills.txt", "r") as f:
            searchlines = f.readlines()
        j = len(searchlines) - 1
        for i, line in enumerate(searchlines):
            if Id_input in str(line):  # I also try to check in this way (Id_input == str(line)), but it didn't work
                k = min(i + 7, j)
                for l in searchlines[i:k]: print l,
                print
            else:
                absent_input = (raw_input("|----Order was not founded----|\n|----Press 'Enter' to continue...----|\n"))
                report_module = ReportModule()
                report_module.show_report()

【问题讨论】:

标签: python file search


【解决方案1】:

检查以下代码。

Id_input = (raw_input("Enter ID of order\n")).strip()
try:
    f = open("Bills.txt", "r")
    print_rows = False
    for idline in f:
        if idline.strip() == Id_input:
           print_rows = True
           continue
        if print_rows:
            if idline.startswith("["): 
                 print idline
            else:
                 break

    if not print_rows:
        absent_input = (raw_input("|----Order was not founded----|\n|----    Press 'Enter' to continue...----|\n"))
        report_module = ReportModule()
        report_module.show_report()
except IOError:
        absent_input = (raw_input("|----File was not founded----|\n|----    Press 'Enter' to continue...----|\n"))
        report_module = ReportModule()
        report_module.show_report()

【讨论】:

  • 我遇到了一个错误,AttributeError: 'str' object has no attribute 'stripe'
  • 我的错,错别字!,再检查一遍,str.strip() 将任何空白区域划出,以便于比较
  • 嗯,这段代码不起作用,我输入ID后关闭程序,但是如果删除if idline.startswith("["): print idline else: break中的else,程序会显示找到块的总价格,它确实有效好。但需要找到一种方法来显示接下来的 6 行)
  • 你是对的,它必须再循环一次,再检查一遍
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
相关资源
最近更新 更多