2015-02-11 79 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 

免責聲明:我在移動設備上,從而不能測試的正確性

相關問題