Как удалить hashtag, @user, ссылку твита, используя регулярное выражение
Мне нужно предварительно обработать твиты с помощью Python. Теперь мне интересно, что будет регулярным выражением, чтобы удалить все хэштеги, @user и ссылки твита соответственно?
например,
-
original tweet: @peter I really love that shirt at #Macy. http://bet.ly//WjdiW4
- обработанное твит:
I really love that shirt at Macy
- оригинальное твит:
@shawn Titanic tragedy could have been prevented Economic Times: Telegraph.co.ukTitanic tragedy could have been preve... http://bet.ly/tuN2wx
- обработанное твит:
Titanic tragedy could have been prevented Economic Times Telegraph co ukTitanic tragedy could have been preve
- оригинальное твит:
I am at Starbucks http://4sh.com/samqUI (7419 3rd ave, at 75th, Brooklyn)
- обработанное твит:
I am at Starbucks 7419 3rd ave at 75th Brooklyn
Мне просто нужны содержательные слова в каждом Tweet. Мне не нужно имя пользователя или любые ссылки или любые пунктуации.
Ответы
Ответ 1
Следующий пример - близкое приближение. К сожалению, нет правильного способа сделать это только через регулярное выражение. Следующие регулярные выражения представляют собой только строки URL (а не только http), любые пунктуации, имена пользователей или любые не буквенно-цифровые символы. Он также отделяет слово одним пространством. Если вы хотите разобрать твит, поскольку вы намереваетесь, вам нужно больше интеллекта в системе. Некоторые предварительные алгоритмы самообучения с учетом отсутствия стандартного формата подачи твитов.
Вот что я предлагаю.
' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
и вот результат на ваших примерах
>>> x="@peter I really love that shirt at #Macy. http://bit.ly//WjdiW4"
>>> ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
'I really love that shirt at Macy'
>>> x="@shawn Titanic tragedy could have been prevented Economic Times: Telegraph.co.ukTitanic tragedy could have been preve... http://bit.ly/tuN2wx"
>>> ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
'Titanic tragedy could have been prevented Economic Times Telegraph co ukTitanic tragedy could have been preve'
>>> x="I am at Starbucks http://4sq.com/samqUI (7419 3rd ave, at 75th, Brooklyn) "
>>> ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
'I am at Starbucks 7419 3rd ave at 75th Brooklyn'
>>>
и вот несколько примеров, где он не идеален
>>> x="I c RT @iamFink: @SamanthaSpice that my excited face and my regular face. The expression never changes."
>>> ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
'I c RT that s my excited face and my regular face The expression never changes'
>>> x="RT @AstrologyForYou: #Gemini recharges through regular contact with people of like mind, and social involvement that allows expression of their ideas"
>>> ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
'RT Gemini recharges through regular contact with people of like mind and social involvement that allows expression of their ideas'
>>> # Though after you add # to the regex expression filter, results become a bit better
>>> ' '.join(re.sub("([@#][A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
'RT recharges through regular contact with people of like mind and social involvement that allows expression of their ideas'
>>> x="New comment by diego.bosca: Re: Re: wrong regular expression? http://t.co/4KOb94ua"
>>> ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x).split())
'New comment by diego bosca Re Re wrong regular expression'
>>> #See how miserably it performed?
>>>
Ответ 2
Это будет работать с вашими примерами. Если у вас есть ссылки внутри ваших твитов, он будет терпеть неудачу, жалко.
result = re.sub(r"(?:@\S*|#\S*|http(?=.*://)\S*)", "", subject)
Edit:
работает с внутренними ссылками, если они разделены пробелом.
Просто пойдите с API. Зачем изобретать колесо?
Ответ 3
Немного поздно, но это решение предотвращает ошибки пунктуации, такие как # hashtag1, # hashtag2 (без пробелов), и реализация очень проста
import re,string
def strip_links(text):
link_regex = re.compile('((https?):((//)|(\\\\))+([\w\d:#@%/;$()~_?\+-=\\\.&](#!)?)*)', re.DOTALL)
links = re.findall(link_regex, text)
for link in links:
text = text.replace(link[0], ', ')
return text
def strip_all_entities(text):
entity_prefixes = ['@','#']
for separator in string.punctuation:
if separator not in entity_prefixes :
text = text.replace(separator,' ')
words = []
for word in text.split():
word = word.strip()
if word:
if word[0] not in entity_prefixes:
words.append(word)
return ' '.join(words)
tests = [
"@peter I really love that shirt at #Macy. http://bet.ly//WjdiW4",
"@shawn Titanic tragedy could have been prevented Economic Times: Telegraph.co.ukTitanic tragedy could have been preve... http://bet.ly/tuN2wx",
"I am at Starbucks http://4sh.com/samqUI (7419 3rd ave, at 75th, Brooklyn)",
]
for t in tests:
strip_all_entities(strip_links(t))
#'I really love that shirt at'
#'Titanic tragedy could have been prevented Economic Times Telegraph co ukTitanic tragedy could have been preve'
#'I am at Starbucks 7419 3rd ave at 75th Brooklyn'
Ответ 4
Я знаю, что это не регулярное выражение, но:
>>>
>>> import urlparse
>>> string = '@peter I really love that shirt at #Macy. http://bit.ly//WjdiW#'
>>> new_string = ''
>>> for i in string.split():
... s, n, p, pa, q, f = urlparse.urlparse(i)
... if s and n:
... pass
... elif i[:1] == '@':
... pass
... elif i[:1] == '#':
... new_string = new_string.strip() + ' ' + i[1:]
... else:
... new_string = new_string.strip() + ' ' + i
...
>>> new_string
'I really love that shirt at Macy.'
>>>