2017-03-02 82 views
-1

我想在第二個位置中發現.之後放置<br>,如下所示。如何將br標籤放在第二個位置的點後

str = "Lorem ipsum amet. consectetur adipisicing elit. sed do eiusmod magna aliqua. Ut enim ad minim veniam. Lorem ipsum amet. consectetur adipisicing elit. sed do eiusmod magna aliqua. Ut enim ad minim veniam." 

預計業績:

str = "Lorem ipsum amet. consectetur adipisicing elit. <br> sed do eiusmod magna aliqua. Ut enim ad minim veniam. Lorem ipsum amet. <br> consectetur adipisicing elit. sed do eiusmod magna aliqua. <br> Ut enim ad minim veniam." 

我嘗試使用這個腳本:

s = "During a November 2014 trip to Los Angeles. Boston-based Snapchat creator. Mike Platco stopped by Snap's Venice. CA offices to say hello." 
index = [i for i,c in enumerate(s) if c=='.'] 
data = [] 
for x in index: 
    text = s[:x*2].replace('. ', '. <br>') 
    data.append(text) 

print data 

結果:

['During a November 2014 trip to Los Angeles. <br>Boston-based Snapchat creator. <br>Mike Plat', "During a November 2014 trip to Los Angeles. <br>Boston-based Snapchat creator. <br>Mike Platco stopped by Snap's Venice. <br>CA offices to say hello.", "During a November 2014 trip to Los Angeles. <br>Boston-based Snapchat creator. <br>Mike Platco stopped by Snap's Venice. <br>CA offices to say hello.", "During a November 2014 trip to Los Angeles. <br>Boston-based Snapchat creator. <br>Mike Platco stopped by Snap's Venice. <br>CA offices to say hello."] 
+1

那麼你有什麼嘗試,究竟是什麼問題呢? – jonrsharpe

+0

@jonrsharpe我仍然困惑,試試看。希望在這裏我可以找到一種方法來處理這種情況。 –

+0

這不是一個代碼寫作或教程服務。參加[遊覽],學習[問]。 – jonrsharpe

回答

-1

正則表達式彈簧在腦海中,但你也可以使用舊的加入和分裂。

source = "Lorem ipsum amet. consectetur adipisicing elit. sed do eiusmod magna aliqua. Ut enim ad minim veniam. Lorem ipsum amet. consectetur adipisicing elit. sed do eiusmod magna aliqua. Ut enim ad minim veniam." 
#break it up into a list separated by dots 
split_src = source.split(".") 
#loop through the list modifying every second one 
for i in range(2, len(split_src)-1, 2): 
    split_src[i] = "<br>" + split_src[i] 
#join the lines up again with a dot 
result = ".".join(split_src) 

誠然,沒有檢查上面是否有超過2個短語(這意味着如果源只有2個短語索引[2]會失敗),但你應該明白我的意思。

+0

感謝您的回覆。但是,我想在秒後加上br,等等。 –

+0

編輯添加範圍循環步進每隔一個點 – Will

+0

謝謝你會,我會在這種情況下開發你的需求的腳本。 –

相關問題