Hướng dẫn dùng tqdm enumerate python

Tôi không thể thấy thanh tiến trình tqdm khi tôi sử dụng mã này để lặp lại tệp đã mở của mình:

        with open(file_path, 'r') as f:
        for i, line in enumerate(tqdm(f)):
            if i >= start and i <= end:
                print("line #: %s" % i)
                for i in tqdm(range(0, line_size, batch_size)):
                    # pause if find a file naed pause at the currend dir
                    re_batch = {}
                    for j in range(batch_size):
                        re_batch[j] = re.search(line, last_span)

cách phù hợp để sử dụng tqdm ở đây là gì?

  • python
  • progress-bar
  • enumerate
  • tqdm

33 hữu ích 2 bình luận 38k xem chia sẻ

answer

41

Hướng dẫn dùng tqdm enumerate python

Bạn đang đi đúng hướng. Bạn đang sử dụng tqdm đúng cách, nhưng dừng việc in từng dòng bên trong vòng lặp khi sử dụng tqdm. Bạn cũng sẽ muốn sử dụng tqdm trên vòng lặp for đầu tiên của mình chứ không phải trên những người khác, như vậy:

with open(file_path, 'r') as f:
    for i, line in enumerate(tqdm(f)):
        if i >= start and i <= end:
            for i in range(0, line_size, batch_size):
                # pause if find a file naed pause at the currend dir
                re_batch = {}
                for j in range(batch_size):
                    re_batch[j] = re.search(line, last_span)

Một số lưu ý khi sử dụng enumerate và cách sử dụng nó trong tqdm tại đây .

41 hữu ích 0 bình luận chia sẻ

answer

16

Hướng dẫn dùng tqdm enumerate python

Tôi cũng gặp phải vấn đề này - tqdm không hiển thị thanh tiến trình, vì số dòng trong đối tượng tệp chưa được cung cấp.

Các forvòng lặp sẽ lặp qua đường dây, đọc đến khi ký tự xuống dòng tiếp theo là gặp phải.

Để thêm thanh tiến trình vào tqdm, trước tiên bạn cần quét tệp và đếm số dòng, sau đó chuyển nó đến tqdm dưới dạngtotal

from tqdm import tqdm

num_lines = sum(1 for line in open('myfile.txt','r'))
with open('myfile.txt','r') as f:
    for line in tqdm(f, total=num_lines):
        print(line)

16 hữu ích 0 bình luận chia sẻ

answer

6

Hướng dẫn dùng tqdm enumerate python

Tôi đang cố gắng làm điều tương tự trên một tệp chứa tất cả các bài viết trên Wikipedia. Vì vậy, tôi không muốn đếm tổng số dòng trước khi bắt đầu xử lý. Ngoài ra, nó là một tệp nén bz2, vì vậy len của dòng được giải nén sẽ đánh giá quá cao số byte được đọc trong lần lặp đó, vì vậy ...

with tqdm(total=Path(filepath).stat().st_size) as pbar:
    with bz2.open(filepath) as fin:
        for line in fin:
            pbar.update(fin.tell() - pbar.n)
    
    # used this to figure out the attributes of the pbar instance
    # print(vars(pbar))

Cảm ơn Yohan Kuanke vì câu trả lời đã xóa của bạn. Nếu người kiểm duyệt phục hồi nó, bạn có thể đóng cũi của tôi.

6 hữu ích 0 bình luận chia sẻ

answer

0

Hướng dẫn dùng tqdm enumerate python

Trong trường hợp đọc tệp với readlines(), bạn có thể sử dụng như sau:

from tqdm import tqdm
with open(filename) as f:
    sentences = tqdm(f.readlines(),unit='MB')

những unit='MB'có thể được thay đổi để 'B' hoặc 'KB' hoặc 'GB' cho phù hợp.

0 hữu ích 0 bình luận chia sẻ

Hướng dẫn dùng tqdm enumerate python

Đăng nhập để trả lời câu hỏi

Có thể bạn quan tâm

Hướng dẫn dùng tqdm enumerate python

If you are reading from a very large file, try this approach:

from tqdm import tqdm
import os

file_size = os.path.getsize(filename)
lines_read= []
pbar = tqdm.tqdm(total=file_zize, unit="MB")
with open(filename, 'r', encoding='UTF-8') as file:
    while (line := file.readline()):
        lines_read.append(line)
        pbar.update(s.getsizeof(line)-sys.getsizeof('\n'))
pbar.close()

I left out the processing you might want to do before the append(line)

EDIT:

I changed len(line) to s.getsizeof(line)-sys.getsizeof('\n') as len(line) is not an accurate representation of how many bytes were actually read (see other posts about this). But even this is not 100% accurate as sys.getsizeof(line) is not the real length of bytes read but it's a "close enough" hack if the file is very large.

I did try using f.tell() instead and subtracting a file pos delta in the while loop but f.tell with non-binary files is very slow in Python 3.8.10.

As per the link below, I also tried using f.tell() with Python 3.10 but that is still very slow.

If anyone has a better strategy, please feel free to edit this answer but please provide some performance numbers before you do the edit. Remember that counting the # of lines prior to doing the loop is not acceptable for very large files and defeats the purpose of showing a progress bar altogether (try a 30Gb file with 300 million lines for example)

Why f.tell() is slow in Python when reading a file in non-binary mode https://bugs.python.org/issue11114