簡體   English   中英

如何使用Python用隨機數替換文件中的數字?

[英]How to replace numbers in file with random ones using 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

(所有數字都在notepad ++中的單行中,並且包含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

randint給出一個int ,需要將其轉換為str

試試outfile.write(line.replace(str(randnum1), str(randnum2)))

就如此容易 :)

該錯誤正好說明了問題所在: TypeError: Can't convert 'int' object to str implicitly 發出該消息是因為randnum1randnum2int而不是str

您必須通過調用str(randnum1)str(randnum2)將它們轉換為str ,例如:

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))

注意:建議不要將一個變量名與多個值類型一起使用多次,因為這樣會使代碼的可讀性降低。 但是,在這種情況下,它只能重復使用一次,因此不會對可讀性造成很大的損害。

萬一您發現它有用,可以采用以下方法。 這首先讀取您的單行並將其拆分為列表。 然后,它從列表中選擇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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM