2016-04-06 33 views
0

我有一個包含在這種格式號的文件:如何使用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 

(所有數字爲在記事本++單個包裝線,它包含的2位數字組1,5k,與之間的空間)

我想要做的是每次運行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 
+0

使用str。 outfile.write(line.replace(str(randnum1),str(randnum2))) – Kajal

+0

我會說str(randnum1),str(randum2)因爲replace需要一個字符串。 – Philipp

+0

請注意,'randnum1'和'randnum2' ints,replace會使用字符串。使用'str(randnum1)'和'str(randnum2)' – vmg

回答

1

錯誤究竟說的是什麼問題:TypeError: Can't convert 'int' object to str implicitly。它的發行是因爲randnum1randnum2int s而不是str s。

您必須通過撥打電話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)) 

注意:它不建議使用多個值類型使用一個變量名多次,因爲它使得代碼的可讀性。但是,在這種情況下,它會被重複使用一次,所以它不會嚴重損害可讀性。

3

randint給出int,需要將其轉換爲str

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

就這麼簡單:)

+0

將用另一個替換隨機數.. –

+2

@xi_這正是OP想要做的。 – Arpan

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)) 
相關問題