我有一个脚本,其中包含与字典中的匹配键有关的索引。最近的更改要求我将所有数字都转换为1(每个数字加1)。例如,如果文件包含以下内容:Python:如何将1添加到文件中的每个整数
form['formA'] = {
'title': 'titleA',
'number': 3,
'numbers': [1,2,4,5]
}
form['formB'] = {
'title': 'titleB',
'number': 7,
'numbers': [8,9,10,11]
}
我希望每个整数都是一个更大的整数。因此,这将成为:
form['formA'] = {
'title': 'titleA',
'number': 4,
'numbers': [2,3,5,6]
}
form['formB'] = {
'title': 'titleB',
'number': 8,
'numbers': [9,10,11,12]
}
所有类型的错误之间,属性错误,只是销毁的格式,我无法弄清楚如何做到这一点。这可能是我最接近的尝试:
#read from the file
f = open(currdir, 'r')
content = f.readlines()
f.close()
addbrackets = False #is it a list
for line in content:
if "form" not in line:
#grab only the values to the right of the colon
rightside = line.split(":")[-1]
list_of_nums = rightside
#remove brackets
if "[" in rightside:
addbrackets = True
removebrackets = rightside.replace("[","").replace("]","")
list_of_nums = removebrackets.split(",")
#search for all integers in the list and add 1
for num in list_of_nums:
if type(num) is int:
num += 1
numindex = list_of_nums.index(num)
list_of_nums[numindex] = num
#plug new values into content
lineindex = content.index(line)
if addbrackets:
content[lineindex] = line.replace(rightside, "[" + ",".join(list_of_nums))[:-1] + "],"
addbrackets = False
else:
content[lineindex] = line.replace(rightside, "".join(list_of_nums))
#write to the new file
f = open(newdir, 'w')
f.write("".join(content))
f.close()
但是,这只是设法弄乱格式。有没有办法做到这一点?
谢谢。
你把等号'='在您例如文件,并使用冒号':'在你的脚本。我猜想有一个错误,但是哪一个?你能确定整数总是在括号内,并且列表总是在一行中? – 2015-01-09 18:24:04
他们应该是冒号,对此感到抱歉。每个密钥对于列表或数字都是唯一的。此外,名单不一定在同一行 - 好点。 – user2869231 2015-01-09 18:34:33
该数据看起来像JSONish。在快速和肮脏的正则表达式之外回答如下:“正确的”解决方案很可能运行或编写解析器来构造数据,然后在更改后将其写回。 – 2015-01-09 18:40:02