gpt4 book ai didi

python - 迭代 .txt 中的行并循环每个 "15 rows"

转载 作者:行者123 更新时间:2023-12-01 03:51:30 24 4
gpt4 key购买 nike

我的 python 脚本有问题。我找不到一种方法来仅计算前 15 行,然后仅计算第二个 15 行,然后仅计算第三个 15 行...这些行来自 txt 文件。

with open('/Users/sammtt/data/test2.txt','r') as f:
for line in nonblank_lines(f):
print(my_txt(line,0))
print(my_txt(line,2))

print(my_txt(line,6))
print(my_txt(line,8))

非常感谢

最佳答案

你可以使用这个recipe对于 itertools来自标准库:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)

将其应用到您的代码中:

with open('/Users/sammtt/data/test2.txt','r') as f:
for chunk in grouper(nonblank_lines(f), 15):
process_chunk(chunk)

关于python - 迭代 .txt 中的行并循环每个 "15 rows",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38172501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com