如何用Python随机替换文件中的数字?

时间:2016-04-06 12:01:24

标签: python

我有一个包含此格式数字的文件:

78 23 69 26 56 59 74 45 94 28 37 
62 52 84 27 12 95 86 86 12 89 92
43 84 88 22 31 25 80 40 59 32 98

(所有数字都在记事本++中的一条包裹线上,它包含1,5k的2位数字组,中间有空格)

我想要做的是每次运行Python代码时随机化一些数字,所以第二个.tmp文件将是唯一的,但保持相同的格式。

所以我尝试了这个并且工作了,但是使用静态数字:12作为搜索,55作为目标。

infile = open('file.txt', 'r')
outfile = open('file.txt.tmp', 'w')
for line in infile:
    outfile.write(line.replace('12', '55'))

infile.colse()
outfile.colse()

然而,为了更好的随机化,我想要做的是使用10-99之间的随机数而不是12和55之类的静态数。

所以我试图做的(并且失败了)是将静态的12和55数字替换成随机的数字:

randnum1 = randint(10,99)
randnum2 = randint(10,99)

infile = open('file.txt', 'r')
outfile = open('file.txt.tmp', 'w')
for line in infile:
    outfile.write(line.replace(randnum1, randnum2))

我收到了这个错误:

Traceback (most recent call last):
  File "<pyshell#579>", line 2, in <module>
    outfile.write(line.replace(randnum1, randnum2))
TypeError: Can't convert 'int' object to str implicitly

3 个答案:

答案 0 :(得分:3)

randint提供int,需要将其转换为str

尝试 outfile.write(line.replace(str(randnum1), str(randnum2)))

就这么简单:)

答案 1 :(得分:1)

错误确切地说明问题所在:TypeError: Can't convert 'int' object to str implicitly。它的发布是因为randnum1randnum2int而不是str s。

您必须通过致电strstr(randnum1)将其转换为str(randnum2),例如像这样:

randnum1 = randint(10,99)
randnum2 = randint(10,99)
randnum1 = str(randnum1)
randnum2 = str(randnum2)

infile = open('file.txt', 'r')
outfile = open('file.txt.tmp', 'w')
for line in infile:
    outfile.write(line.replace(randnum1, randnum2))

注意:建议不要多次使用一个变量名称和多个值类型,因为它会降低代码的可读性。但是,在这种情况下,它会重复使用一次,因此不会对可读性造成太大影响。

答案 2 :(得分:0)

万一你发现它有用,你可以采取以下方法。这首先读取您的单行并将其拆分为一个列表。然后,它会从列表中选择10个随机条目,并使用1099之间的新随机数替换该条目。最后,它将新数据写回文件。

from random import randint

with open('input.txt') as f_input:
    data = f_input.readline().split()
    entries = len(data) - 1

for _ in xrange(10):
    data[randint(0, entries)] = str(randint(10, 99))

with open('input.txt', 'w') as f_output:
    f_output.write(' '.join(data))