我希望能够将相同的字符串集替换为随机的新100.

出发地:

color = { 0 0 0 }

致:

color = { 2 5 10 }

color = { 1 59 102 }

color = { 9 72 200 }

在文本文件的每一行上.

以下是我的python代码.

import random

for i in range(0, 10):
    x = str(random.randrange(0, 256))
    y = str(random.randrange(0, 256))
    z = str(random.randrange(0, 256))

    with open("9.txt", "r") as file:
        file_data = file.read()

    file_data = file_data.replace("color = { 0 0 0 }", "color = { " + x + " " + y + " " + z + " }")

    with open("colored.txt", "w") as file:
        file.write(file_data)

此代码全部正确更改,但更改为相同的值,并且我希望它是唯一的数字.

推荐答案

您需要逐行处理文件,而不是一次处理所有文件,并为每行生成新的随机数.

with open("9.txt", "r") as infile, open("colored.txt", "w") as outfile:
    for line in infile:
        x = str(random.randrange(0, 256))
        y = str(random.randrange(0, 256))
        z = str(random.randrange(0, 256))
        line = line.replace("color = { 0 0 0 }", f'color = {{ {x} {y} {z} }}')
        outfile.write(line)

Python相关问答推荐

仅使用2种 colored颜色 创建热图

Flask:如何在完整路由代码执行之前返回验证

在Docker中运行HAProxy时无法获得503服务

避免循环的最佳方法

如何将新的SQL服务器功能映射到SQL Alchemy的ORM

使用Python和PRNG(不是梅森龙卷风)有效地生成伪随机浮点数在[0,1)中均匀?

具有多个选项的计数_匹配

Pandas 第二小值有条件

如何使用pandasDataFrames和scipy高度优化相关性计算

将jit与numpy linSpace函数一起使用时出错

如何避免Chained when/then分配中的Mypy不兼容类型警告?

_repr_html_实现自定义__getattr_时未显示

删除所有列值,但判断是否存在任何二元组

海上重叠直方图

Scrapy和Great Expectations(great_expectations)—不合作

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

基于形状而非距离的两个numpy数组相似性

如何使用两个关键函数来排序一个多索引框架?

在输入行运行时停止代码