我需要混合我的数据。我在一个文件中有一些数字,我需要将它们混合,例如,将 20 上的所有 4 都更改,但不要将 14 更改为 120。我想了很多,但我不确定是否可行,因为有很多数字,我需要用随机值替换一百次。 有人做过这样的事吗?任何人都知道这是可能的?
最佳答案
这是一个可能对您有所帮助的 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()
示例:
file.txt 包含:4 14 4 444 20
Output.txt 将是:60 14 60 444 20
,考虑到随机生成的整数是 60
。
重要:在这个例子中,我认为你的文件只包含正数。因此,您将必须修改正则表达式以获得负数,如果您有数字以外的字符,请稍微更改一下。
这可能不是您需要的方式,但我认为这是一个好的开始。
关于python - 在 Python/C++ 的变化文件中用随机数替换数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50210087/