标题可能有点神秘,所以我将在这里详细说明。
我有一个定义如下的对象的列表:
pname {
'amondo': 'amondo',
'android13': 'android13',
'android13s': 'android13s',
'android14': 'android14',总共351个物体。
我想要做的是用从1开始的数字替换左边引号中的文本。所以最终的结果应该是:
'1': 'amondo',
'2': 'android13',
'3': 'android13s',
'4': 'android14',一直到最后一个物体。
我用以下代码创建了一个python脚本:
import re
f = open('name.js', 'r')
inp = []
outp = []
for i in f:
inp.append(i)
for i in inp:
x = 1
while x < 352:
r = re.sub('.*\:', "'" + str(x) + "':", i)
x+=1
outp.append(r)
o = open('done.js', 'w')
for i in outp:
o.write(i)
f.close()
o.close()但产出如下:
'351': 'amondo',
'351': 'android13',
'351': 'android13s',
'351': 'android14',我明白我做错了什么,为什么输出就是它,但我不知道如何修复它。
可能有一种功能可以帮助我,但我不知道。
发布于 2015-10-22 04:41:13
如果你仔细观察你的then循环,直到x=352才停止它,然后追加r,这不是你想要的.计数行的一种简单方法是使用枚举:
for x,i in enumerate(f):
r = re.sub('.*\:', "'" + str(x) + "':", i)
outp.append(r)发布于 2015-10-22 04:37:13
试试这个:
with open('name.js') as infile, open('done.js', 'w') as outfile:
count = 0
for line in infile:
if ":" not in line:
outfile.write(line)
continue
count += 1
_, val = line.strip().split(":")
outfile.write("'{}' : {}\n".format(count, val))https://stackoverflow.com/questions/33273441
复制相似问题