代码之家  ›  专栏  ›  技术社区  ›  Jacob Fuchs

从python生成器打印所有结果

  •  1
  • Jacob Fuchs  · 技术社区  · 7 年前

    我做了一个生成器函数,它使用关键字搜索csv文件,如果有什么结果,我想打印出来。我怎样才能在不反复使用打印(下一代(gen_results))的情况下做到这一点?

    我尝试了一个stopIteration的try-catch语句,当关键字与联系人不匹配时,我希望有一个更简洁的解决方案。

    def search(keyword, filename):
        f = open(filename, 'r')
        for line in f:
            if keyword in line:
                yield line
        f.close()
    
    the_generator = search('Python', 'contacts.csv')
    print(next(the_generator))
    print(next(the_generator))  
    
    contacts.csv
    Name01, 89888
    Name02, 8885445
    Name03, 54555
    Name04, 55544584
    Name05, 55855
    Python, 100
    BigPi, 444
    Python, 101
    

    如果关键字没有联系人,我希望输出是一个“NothingFound”语句。如果有带有关键字的联系人,它将输出所有列表。

    4 回复  |  直到 7 年前
        1
  •  0
  •   Patrick Artner    7 年前

    有几种方法可以消耗发电机运行 next() 只消耗它的(下一个)值。

    生成文件:

    def gen_file():
        with open("contacts.csv","w") as f:
            f.write("""Name01, 89888
    Name02, 8885445
    Name03, 54555
    Name04, 55544584
    Name05, 55855
    Python, 100
    BigPi, 444
    Python, 101
    """)
    

    使用它:

    gen_file()   
    
    def search(keyword, filename="contacts.csv"):
        """Changed to use .. with open() as f: ... style syntax."""
        with open(filename, 'r') as f:
            for line in f:
                if keyword in line:
                    yield line 
    
    
    # consume all of it into a list - you can reuse it
    print("-"*40)
    the_generator = search('Python', 'contacts.csv')
    contacts = list(the_generator)
    print(*contacts, sep="")
    
    
    print("-"*40)
    # decompose the generator directly for printing
    the_generator = search('Python', 'contacts.csv')
    print(*the_generator, sep="" ) 
    
    
    print("-"*40)
    # use a for loop over the generated results
    the_generator = search('Python', 'contacts.csv')
    for li in the_generator:
        print(li, end="") # remove end=\n
    
    
    print("-"*40)
    # using str.join to create the output
    the_generator = search('Python', 'contacts.csv')
    print("".join(the_generator))
    
    
    print("-"*40)
    # loop endlessly until StopIteration is raised
    try:
        while True:
            print(next(the_generator), end="")
    except StopIteration:
        pass
    

    等。

    输出(几次):

    ----------------------------------------
    Python, 100
    Python, 101
    

    如果不重用生成的值,则“最佳”值可能是 print(*the_generator,sep="") 或者更明确地说:

    # use a for loop over the generated results
    the_generator = search('Python', 'contacts.csv')
    for li in the_generator:
        print(li,end="") # remove end=\n
    

    您也可以在这里阅读: Using yield from with conditional in python

        2
  •  2
  •   BlueSheepToken    7 年前

    请试试这个

    def search(keyword, filename):
        f = open(filename, 'r')
        for line in f:
            if keyword in line:
                yield line
            else:
                yield 'Nothing Found'
        f.close()
    
    the_generator = search('Python', 'contacts.csv')
    for g in the_generator:
        print(g)
    

    “the_generator”是一个迭代对象,“for”循环需要一个迭代对象才能运行。程序输出将:

    Nothing Found
    Nothing Found
    Nothing Found
    Nothing Found
    Nothing Found
    Python, 100 
    
        3
  •  1
  •   Bitto    7 年前
    def search(keyword, filename):
        f = open(filename, 'r')
        for line in f:
            if keyword in line:
                yield line
        f.close()
    
    the_generator = search('Python', 'contacts.csv')
    my_list=list(the_generator)
    if not my_list:
        print("Not Found")
    for item in my_list:
        print(item.strip())
    
        4
  •  1
  •   hpaulj    7 年前

    您可以将“未找到”测试放入生成器本身:

    def search(keyword, lines):
        cnt = 0
        for line in lines:
            if keyword in line:
                cnt += 1
                yield line
        if cnt==0:
            yield "NOT FOUND"
    
    In [166]: txt = """Name01, 89888
         ...: Name02, 8885445
         ...: Name03, 54555
         ...: Name04, 55544584
         ...: Name05, 55855
         ...: Python, 100
         ...: BigPi, 444
         ...: Python, 101
         ...: """.splitlines()
    In [167]: for x in search("Python",txt):print(x)
    Python, 100
    Python, 101
    In [168]: for x in search("Foobar",txt):print(x)
    NOT FOUND
    

    否则我认为最简单的是 list 并检查空列表。生成器机制本身不计算 yields .