2015-02-11 27 views
0

我有一个正常的列表,并且我想每25个索引(由第二个索引开始)更改该列表的元素。所以我创建了一个循环来生成该数字并将其存储在一个列表中(即2,27,52,77 ....)。然后我打印了该索引的每一项,但现在我似乎无法找到与re.sub一起工作的方法。 我想用新的元素替换这些元素,然后将列表中的所有项目(不仅仅是我更改的)写入文件中。替换该索引中的每个项目并写入文件

因此我们的目标是使用应用re.sub或一些其他方法来代替:

' Title     =' by ' Author     =' 

如何实现这一目标?

这里是我的代码:

counter = 0   
length = len(flist) # Max.Size of List 
ab = [2] 

for item in flist: 
    counter +=1  
    a = ((25*counter)+2) #Increment 
    ab.append(a) 
    if a >= length: 
     ab.pop() #Removing last item 
     break 

for i in ab: 
    print(flist[i-1]) #Printing element in that index 
    #replace item 

#write to file 
fo = open('somefile.txt', 'w') 
for item in flist:  
fo.write(item) 

fo.close() 

PS:我是新来的蟒蛇,sugestions和批评得多apreciated!

回答

1

匹配的文本可以使用:

new_str = re.sub(r'\s+Title\s+=', 'Author     =', old_str) 

\s意味着空白,+意味着一个或多个。您可以使用\s{4}来精确匹配4个空格,也可以使用任意数量的空格。更多信息here

或者,你可以使用replace()

new_str = old_str.replace(' Title     =', 'Author     =') 

您可以使用range()简化代码位的其余部分。 range()有3个参数,其中2个是可选的;开始,结束,一步。

for i in range(2, 200, 25): 
    print(i) 

最后,你可以使用with open()代替open()

with open('my_file.txt', 'w') as fo: 
    # Do stuff here. 
    .... 
    .... 
    # File closes automatically. 
+0

如何使用我们现在创建的项目替换上一个项目? – dbpyth 2015-02-11 18:48:06

+0

're.sub()'创建一个新的字符串。我编辑了代码以说清楚。你简单的使用'new_str'。 – 2015-02-11 18:48:53

+1

这两种方法的工作就像一个魅力:D我的问题是,在我们取代之后,我们如何删除旧的并在同一个地方写入新的?对不起,混淆 – dbpyth 2015-02-11 18:57:16

0

喜欢的东西:

for i in ab: 
    fixed = re.sub("/ Title     =/", " Author     =", flist[i-1]) 
    print(fixed) #Printing replaced line 

免责声明:我在移动设备上,从而不能测试的正确性

相关问题