简体   繁体   中英

Replacing numbers by random numbers in a changing file in Python/C++

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM