在Python /C++中用随机数替换数字

2024-04-18 01:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要混合我的数据。我在一个文件中有一些数字,我需要它是混合的,例如,改变所有4的20,但不要改变14到120的这样做。我想了很多,我不确定是否可能,因为有很多数字,我需要用一个随机值替换上百次。 有人做过那样的事吗?有人知道这是可能的吗?你知道吗


Tags: 文件数据数字
1条回答
网友
1楼 · 发布于 2024-04-18 01:32:49

下面是一个可以帮助您的python示例:

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

示例:

你知道吗文件.txt包含:4 14 4 444 20

你知道吗输出.txt将是:60 14 60 444 20,考虑到随机生成的整数是60。你知道吗

重要提示:在本例中,我认为您的文件只包含正数。因此,您必须修改regexp以获得负数,如果您有数字以外的字符,则需要对其进行一点更改。你知道吗

这可能不是你需要的方式,但我认为这是一个好的开始。你知道吗

相关问题 更多 >

    热门问题