Py学习  »  Python

python-读取每x行

Zirozia • 5 年前 • 1244 次点击  

我想要的是让5个线程逐行读取文件的内容。 第一个线程必须读取行,我希望线程从不同点开始每5行读取一次。

(Index Pos)
t1 reads >>> 0, 5, 10, 15
t2 reads >>> 1, 6, 11, 16

凡此种种,不一而足。

目前我已经尝试使用模来做这件事,但也有一些问题,如质数15引起的问题。这不是我的最后一个作品,但它是我所展示的,因为我正在使用的是可怕的,没有意义。

def function(n):#Function to generate hash
  count = n
  for line in open('wordlist.txt'):#For each line in a file do this
    if count % 2 == 0:
      linex = line.strip()
      hashed = hashlib.md5(linex.encode()).hexdigest()
      #print(line + ":" + hashed)
      count += 1
    else:
      count += 1

长话短说,我需要一些帮助,我会非常感谢帮助我解决这个问题的人。

只是想在文本文件的行上迭代一些东西。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/44412
 
1244 次点击  
文章 [ 1 ]  |  最新文章 5 年前
larsks
Reply   •   1 楼
larsks    6 年前

这是我建议的一个例子。这个过程是标准的, 向五个工人的集合发送线路。第一个工人会 得到0、5、10、15等线,第二个工人得到1、6、11、16, 等等等等。

import itertools
import queue
import sys
import threading


class Worker(threading.Thread):
    def __init__(self, id, q, **kwargs):
        self.id = id
        self.q = q
        super().__init__(daemon=True, **kwargs)

    def run(self):
        while True:
            # Receive another (line_number, line) tuple from the
            # main thread.
            ln, line = self.q.get()
            if ln == -1:
                break

            print('thread {} processing line {}: {}'.format(self.id, ln, line))


def main():
    workers = []
    queues = []

    # create workers, and for each worker create a queue that will
    # be used to pass data to the worker.
    for i in range(5):
        q = queue.Queue()
        w = Worker(i, q)
        workers.append(w)
        queues.append(q)
        w.start()

    # create a "cycle": an infinite iterator that will loop over
    # the list of queues.
    q_cycle = itertools.cycle(queues)
    for ln, line in enumerate(sys.stdin):
        q = next(q_cycle)
        q.put((ln, line))

    # tell the workers to exit
    for q in queues:
        q.put((-1, None))

    # wait for workers to finish
    for w in workers:
        w.join()


if __name__ == '__main__':
    main()