2013-12-17 126 views
0

我有一個文本,我想從中刪除URL,但我有問題。如何從Python中的字符串中刪除一些URL

document = re.sub('[^a-z]|http:\/\/\w+.\w+\/\w*', ' ', document) 

IGOT: 文件= 'RT @prettycolleges:鳳凰城大學http://t.co/d5wxsy332r好'

>> 'rt prettycolleges university of phoenix http  t co d wxsy r good' 

,但我想這樣的結果:rt prettycolleges university of phoenix good

什麼我應該怎麼做?

回答

0

你可以使用像

一個正則表達式'\ S * HTTP://.* \ s?(查找有一個URL字符串 - HTTP:// - 它與空白結束)

,且因爲子功能取代你在找什麼,代碼應該是:

import re 
document = 'rt @prettycolleges: university of phoenix http://t.co/d5wxsy332r good' 

print re.sub(r'http:\\*/\\*/.*?\s', ' ', document) ## note the r (raw string) 
>> 'rt @prettycolleges: university of phoenix good' 
+0

它只是爲了我所提到的例子中工作,但新的例子實在不行。 document ='rt @beasiswaindo:http:\/\/t.co \/uio40rq8hc beasiswa full s2 w的大學' – user3092781

+0

那是因爲url不是以http://開頭的(你已經跳過了斜槓)。我會編輯我的答案,所以也可以在這種情況下工作 – azuax

相關問題