在文本文件中,我有几千个2000
次出现。我想用1990年到2020年的随机数替换所有出现的事件。我怎么能用正则表达式,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='')
答案 0 :(得分:1)
我没有真正理解你的意思,但如果你想用随机整数替换文件中的特定文本,请尝试:
focus
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='')
希望有所帮助
答案 1 :(得分:0)
您可以使用:
import re
import random
input_file = open('filename.txt', 'r').read()
output_data = re.sub('2000', str(random.randint(1990, 2020)), input_file)