I need to mix my data. I've got some numbers in a file and I need it to be mixed, like for example, change all 4's on 20, but don't change 14's to 120's doing this. I thought a lot and I'm not really sure if it's possible, because there's a big number of digits and I need to do replacement hundred times with a random values. Anyone did something like that? Anyone knows it's possible?
Asked
Active
Viewed 65 times
0
-
Regular expressions should solve your problem. Something like `\D4\D` but more complex, to also catch numbers at beginning and ending of file – Denis Sheremet May 07 '18 at 09:05
-
I suggest you to have a look at this question, which will help to to extract numbers from the string holding the file's content. If you have the number as integers, you don't have the problem anymore : https://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string – souki May 07 '18 at 09:17
-
Just a question though, do you need to change every number to another one? Or for example just all 4's, or all 5's etc.. ? Can the file you are reading contain other things than digits? – souki May 07 '18 at 09:23
-
No, I need to make +/- 100 replacements. Yes, I have only numbers in my file – May 07 '18 at 10:20
1 Answers
1
Here is a python example that might help you :
import re
import random
def writeInFile(fileName, tab): //This function writes the answer in a file
i = 0
with open(fileName, 'a') as n:
while i != len(tab):
n.write(str(tab[i]))
if i + 1 != len(tab):
n.write(' ')
i += 1
n.write('\n');
def main():
file = open('file.txt', 'r').readlines() //Reading the file containing the digits
tab = re.findall(r'\d+', str(file)) //Getting every number using regexp, in string file, and put them in a list.
randomDigit = random.randint(0, 100) // Generating a random integer >= 0 and <= 100
numberToReplace = "4" //Manually setting number to replace
for i in xrange(len(tab)): //Browsing list, and replacing every "4" to the randomly generated integer.
if tab[i] == str(numberToReplace):
tab[i] = str(randomDigit)
writeInFile("output.txt", tab) //Call function to write the results.
if __name__ == "__main__":
main()
Example :
file.txt contains : 4 14 4 444 20
Output.txt will be : 60 14 60 444 20
, considering that the randomly generated integer was 60
.
Important : In this example, I considered that your file is only containing positive numbers. So you will have to modify regexp to get negative numbers, and change it a bit if you have characters other than digits.
It might not be exactly the way you need it, but I think it's a good start.

souki
- 1,305
- 4
- 23
- 39