【问题标题】:Creating multiple text documents in a for loop在 for 循环中创建多个文本文档
【发布时间】:2021-08-03 03:48:57
【问题描述】:

我正在尝试创建一个包含自定义生成单词的文本文件,格式如下:3 个数字+2 个字母+3 个数字 示例:abc00dfeaaa98fff 等。

我可以使用单个文本文件来实现我想要的,但是文件变得如此之大,并且很难处理如此大的文件。如何更改我的代码以便将这些行保存在多个文本文件中?

from itertools import product
i = 1
numbers = ["0","1","2","3","4","5","6","7","8","9"]
characters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
f = open("D:\wordlist" + str(i) + ".txt", "w+")
for a in product(characters, repeat=3):
    for b in product(numbers,repeat=2):
        for c in product(characters, repeat=3):
            word = "".join(a + b + c)
            f.write(word+"\n")
            i += 1
            print(str(i)+"."+word)
            if i > 13824:
                f.close()
                f = open("D:\wordlist" + str(i//13824) + ".txt", "w+")
                continue



f.close()

【问题讨论】:

  • 当您到达13824 时,您可能忘记重置i,此代码看起来会在遇到13824 字时不断打开包含一个字的新文件。
  • @Stidgeon 感谢您的建议,但我并不是要创建随机单词,而是要确保我以有序的方式获得此表单中的所有组合。
  • if i > 13824 应该是 if i % 13824 == 0: 所以它每 13824 行开始一个新文件。
  • 您的新文件名中有一个小错误。当13824 < i < 2*13824 时,str(i//13824) 是什么?它的"1"!那将与您的原始文件具有相同的文件名。将str(i//13824) 更改为str((i//13824) + 1)
  • 为什么不为外循环的每次迭代创建一个新文件?

标签: python for-loop iteration itertools cartesian-product


【解决方案1】:

你已经准备好了一切,只需要一个额外的变量(file_number)来控制你所在的文件。 最后你的代码应该是这样的

from itertools import product
i = 1
file_number = 0
numbers = ["0","1","2","3","4","5","6","7","8","9"]
characters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
f = open("D:\wordlist" + str(file_number) + ".txt", "w+")
for a in product(characters, repeat=3):
    for b in product(numbers,repeat=2):
        for c in product(characters, repeat=3):
            word = "".join(a + b + c)
            f.write(word+"\n")
            i += 1
            print(str(i)+"."+word)
            if i > 13824:
                f.close()
                file_number += 1
                f = open("D:\wordlist" + str(file_number) + ".txt", "w+")
                i = 1
                continue

f.close()

【讨论】:

  • 感谢您的回答,但是另一条评论已解决了该问题而没有添加任何内容。只需将 i > 13824 更改为 i % 13824 = 0 即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多