如何为文件中的每个单词添加数字组合?

时间:2019-10-24 02:03:50

标签: python

我需要在文本文件中的每个单词后附加两位数字的组合(即从00到99)。

例如:

word

成为:

word00
word01
word02
...etc
word99

我有一个文本文件,其中包含数百个单词,最后应具有这两位数字的组合。如何阅读文本文件中的每一行并创建这些新单词?

这就是我到目前为止

import itertools

# open file with words
f = open("createwords.txt", "r")

# read file
altern = f.read()

# store words from file
first_half_password = str(altern)

# numbers to append to word
digits = '0123456789'

for c in itertools.product(digits, repeat=2):
    password = first_half_password+''.join(c)
    print (password)


1 个答案:

答案 0 :(得分:1)

您在这里!

import itertools

digits = '0123456789'
with open("output.txt", "w+") as new_file:
    with open('createwords.txt') as file:
        for line in file:
            for c in itertools.product(digits, repeat=2):
                number = ''.join(i for i in c)
                new_file.write(''.join([line.rstrip(), number, '\n']))

也有一点解释:

for c in itertools.product(digits, repeat=2)-c将返回您想要的数字的元组,即(0,0)。因此,您需要使用下一行的join方法将其解析为适当的数字。最后,您将新行作为三样东西的输出输出到单独的txt文件中:原始行,新数字和一个'\ n'字符,该字符告诉txt文件回车到新行。 / p>

或者,您可以将itertools.product替换为100的迭代,例如r in range(100)并根据blhsing的答案格式化字符串[现在已删除,但基本上是"%02d" % (r,)]或r.zfill(2)

相关问题