【问题标题】:replace the same occurring number with another random number [closed]用另一个随机数替换相同的出现数[关闭]
【发布时间】:2017-04-17 20:26:55
【问题描述】:

在一个文本文件中,我有数千个 2000 出现。我想用 1990 年到 2020 年的随机数替换所有出现的事件。如何在 regex 或 python、notepad++、R 中执行此操作?谢谢。
出现的都是这样的:

"myDate" : "2000_02",

更新:

这里是Kropalis建议的解决方案:

import fileinput
from random import randint
textToReplace = randint(1990, 2020)
textToSearch = 2000
fileToSearch = "C:\data.json"
with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(textToSearch, textToReplace), end='')

但我得到一个语法错误:

print(line.replace(textToSearch, textToReplace), end='')

【问题讨论】:

  • 逐行读取文件,将2000替换为正则表达式,或使用随机模块的其他方法,然后逐行写入另一个文件。
  • 你的意思是你想用一个随机数替换所有出现的地方吗?或者你想用随机数替换每个出现的地方?
  • 您的文件格式是什么? 2000 是用空格还是字符串的子串隔开?
  • @hwnd 它在问题中放了一个例子,更新了它。它最初在 json 文件中。

标签: python r regex notepad++


【解决方案1】:

我并没有真正明白你的意思,但如果你想用随机整数替换文件中的特定文本,请尝试:

import fileinput
from random import randint
with fileinput.FileInput(fileToSearch, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(textToSearch, textToReplace), end='')

textToReplace = randint(1990, 2020)

希望有帮助

【讨论】:

  • 如何在代码中定义myfile.txt?
  • ` fileToSearch = 'C:\Users\User\Desktop\yourfile.txt' ` 或您的文件所在的任何位置
  • 没有 ` 部分。没把它认成代码,所以基本上
  • fileToSearch = 'C:\Users\User\Desktop\yourfile.txt
  • 这里有语法错误:print(line.replace(textToSearch, textToReplace), end='')
【解决方案2】:

你可以使用:

import re
import random

input_file = open('filename.txt', 'r').read()
output_data = re.sub('2000', str(random.randint(1990, 2020)), input_file)

【讨论】:

  • 我如何定义要搜索的条目文件?
  • 更新答案...
  • 我得到了这个打字错误:TypeError: object of type 'int' has no len()
  • randint 转换为字符串...
猜你喜欢
  • 2018-12-08
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 2020-07-13
  • 2020-11-19
  • 2013-11-09
  • 1970-01-01
相关资源
最近更新 更多