我有一個將顯示來自reddit的圖像的應用程序。有些圖像像這樣http://imgur.com/Cuv9oau,當我需要使它們看起來像這樣http://i.imgur.com/Cuv9oau.jpg。只需在開頭添加(i)並在末尾添加(.jpg)。如何修改我在Python中隨機挑選的url
1
A
回答
2
這個功能應該做你所需要的。我擴展了@ jh314的迴應,並且使代碼稍微小一點,並檢查url 開始與http://imgur.com
,因爲該代碼會導致其他URL的問題,例如我所包含的Google搜索。它也只取代了第一例,這可能會導致問題。
def fixImgurLinks(url):
if url.lower().startswith("http://imgur.com"):
url = url.replace("http://imgur", "http://i.imgur",1) # Only replace the first instance.
if not url.endswith(".jpg"):
url +=".jpg"
return url
for u in ["http://imgur.com/Cuv9oau","http://www.google.com/search?q=http://imgur"]:
print fixImgurLinks(u)
給出:
>>> http://i.imgur.com/Cuv9oau.jpg
>>> http://www.google.com/search?q=http://imgur
1
您應該使用Python's regular expressions來放置i
。至於.jpg
,你可以只需append it。
3
你可以使用一個字符串替換:
s = "http://imgur.com/Cuv9oau"
s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "")
此設爲s:
'http://i.imgur.com/Cuv9oau.jpg'
相關問題
- 1. 隨機在python列表中挑選
- 2. 如何挑選隨機陣列中的
- 3. 如何通過挑選隨機變量來在Python中執行隨機事件?
- 4. 挑選隨機值
- 5. ArrayList隨機挑選
- 6. Python的隨機URL選擇
- 7. 如何從Python集合中挑選2個隨機項目?
- 8. Firebase iOS Swift:如何挑選隨機userProfile?
- 9. 在c中挑選隨機數字#
- 10. android挑選隨機圖片?
- 11. Math.Random()挑選隨機數組
- 12. 挑選隨機名稱
- 13. Python - 從3x3 NP陣列中挑選隨機的列或行
- 14. 從4個表中隨機挑選
- 15. 從string.xml中挑選隨機字符串
- 16. 從數組中挑選隨機數
- 17. 從數組中挑選隨機顏色
- 18. 從列表中隨機挑選
- 19. 從數組中挑選隨機NSNumber?
- 20. 隨機挑選3個挑選的數字
- 21. 如何挑選Javascript中的隨機單詞
- 22. 如何從一些中獎號碼中挑選隨機數字?
- 23. 挑選從陣列隨機樣本在python
- 24. 隨機挑選的XMLList菜單項
- 25. 修改腳本以隨機選擇div
- 26. 我如何從列表中隨機挑選出用戶要求在python中使用輸入的次數?
- 27. 根據體重和挑選時間挑選隨機密鑰
- 28. 如何挑選URL中的數字?
- 29. Javascript - 如何從數組中隨機挑選元素?
- 30. 如何從數組中挑選隨機聲音? (JS)
感謝每一位,我結束了使用這個版本。有時我仍然會因爲沒有圖片而導致頁面加載錯誤,我點擊了網址,並且顯示頁面未找到或者有些不同。有沒有辦法爲圖像添加檢查,如果找不到,則跳過它 – gallly
該URL最後有一個額外的'/',所以它是一個無效的URL。你可以在轉換過程中檢查URL是否有效,但是你最好問一個新的問題。 – 2013-07-11 03:58:16
謝謝我添加了代碼來刪除它,到目前爲止它一直在工作! – gallly