Самый быстрый способ получить URL внутри строки - PullRequest
0 голосов
/ 30 марта 2019

Мне нужно проверить тысячи строк, мне нужно получить полный URL-адрес, содержащий instagram.com/p/

Пока я использую этот метод:

msg ='hello there http://instagram.com/p/BvluRHRhN16/'
msg = re.findall(
            'http[s]?://?[\w/\-?=%.]+instagram.com/p/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
            msg)
print(msg)

, но естьопределенные URL, которые он не может найти.

Я хочу получить все URL, подобные приведенным ниже:

https://instagram.com/p/BvluRHRhN16/ https://www.instagram.com/p/BvluRHRhN16/ http://instagram.com/p/BvluRHRhN16/ https://www.instagram.com/p/BvluRHRhN16/ www.instagram.com/p/BvluRHRhN16/

Как я могу получить этот результат самым быстрым способом?

Ответы [ 2 ]

1 голос
/ 30 марта 2019
url = '''
'hello there http://google.com/p/BvluRHRhN16/ this is a test',
      'hello there https://www.instagram.com/p/BvluRHRhN16/',
      'hello there www.instagram.com/p/BvluRHRhN16/ this is a test',
      'hello there https://www.instagram.net/p/BvluRHRhN16/ this is a test'
'''

from urlextract import URLExtract

extractor = URLExtract()
urls = extractor.find_urls(url)
print(urls)

Вывод: ['http://google.com/p/BvluRHRhN16/',' https://www.instagram.com/p/BvluRHRhN16/', 'www.instagram.com/p/BvluRHRhN16/', 'https://www.instagram.net/p/BvluRHRhN16/']

Отредактировано: отфильтроватьURL-адрес

filtered = ([item for item in urls if "instagram.com/p/" in item])

print(filtered)

Вывод: ['https://www.instagram.com/p/BvluRHRhN16/',' www.instagram.com/p/BvluRHRhN16/']

1 голос
/ 30 марта 2019

Я предполагаю, что вход представляет собой список предложений, содержащих URL. Надеюсь, это поможет.

msg =['hello there http://google.com/p/BvluRHRhN16/ this is a test',
      'hello there https://www.instagram.com/p/BvluRHRhN16/',
      'hello there www.instagram.com/p/BvluRHRhN16/ this is a test',
      'hello there https://www.instagram.net/p/BvluRHRhN16/ this is a test'
     ]

for m in msg:
    ms = re.findall('(http.*instagram.+\/p.+|www.*instagram.+\/p.+)',m)
    print(ms)

Отредактированное регулярное выражение:

ms = re.findall('(http.*instagram\.com\/p.+\/|www.*instagram\.com\/p.+\/)',m)
...