Извлечь информационную часть f URL в python - PullRequest
2 голосов
/ 05 апреля 2019

У меня есть список из 200 тыс. URL, с общим форматом:

http[s]://..../..../the-headline-of-the-article
OR
http[s]://..../..../the-headline-of-the-article/....

Число / до и после the-headline-of-the-article варьируется

Вот некоторые примеры данных:

'http://catholicphilly.com/2019/03/news/national-news/call-to-end-affordable-care-act-is-immoral-says-cha-president/',
 'https://www.houmatoday.com/news/20190327/new-website-puts-louisiana-art-on-businesses-walls',
 'https://feltonbusinessnews.com/global-clean-energy-inc-otcpkgcei-climbs-investors-radar-as-key-momentum-reading-hits-456-69429/149601/',
 'http://www.bristolpress.com/BP-General+News/347592/female-music-art-to-take-center-stage-at-swan-day-in-new-britain',
 'https://www.sfgate.com/business/article/Trump-orders-Treasury-HUD-to-develop-new-plan-13721842.php',
 'https://industrytoday.co.uk/it/research-delivers-insight-into-the-global-business-voip-services-market-during-the-period-2018-2025',
 'https://news.yahoo.com/why-mirza-international-limited-nse-233259149.html',
 'https://www.indianz.com/IndianGaming/2019/03/27/indian-gaming-industry-grows-in-revenues.asp',
 'https://www.yahoo.com/entertainment/facebook-instagram-banning-pro-white-210002719.html',
 'https://www.marketwatch.com/press-release/fluence-receives-another-aspiraltm-bulk-order-with-partner-itest-in-china-2019-03-27',
 'https://www.valleymorningstar.com/news/elections/top-firms-decry-religious-exemption-bills-proposed-in-texas/article_68a5c4d6-2f72-5a6e-8abd-4f04a44ee74f.html',
 'https://tucson.com/news/national/correction-trump-investigations-sater-lawsuit-story/article_ed20e441-de30-5b57-aafd-b1f7d7929f71.html',
 'https://www.publicradiotulsa.org/post/weather-channel-sued-125-million-over-death-storm-chase-collision',

Я хочу извлечь только the-headline-of-the-article.

т.

call-to-end-affordable-care-act-is-immoral-says-cha-president
global-clean-energy-inc-otcpkgcei-climbs-investors-radar-as-key-momentum-reading-hits-456-69429
correction-trump-investigations-sater-lawsuit-story

Я уверен, что это возможно, но я относительно новичок в регулярных выражениях в python.

В псевдокоде я думал:

  • разделить все на /

  • сохранить только тот кусок, который содержит -

  • заменить все - на \s

Возможно ли это в python (я питон n00b)?

Ответы [ 3 ]

2 голосов
/ 05 апреля 2019
urls = [...]
for url in urls:
    bits = url.split('/') # Split each url at the '/'
    bits_with_hyphens = [bit.replace('-', ' ') for bit in bits if '-' in bit] # [1]
    print (bits_with_hyphens)

[1] Обратите внимание, что ваш алгоритм предполагает, что только один из фрагментов после разделения URL будет иметь дефис, что неверно, учитывая ваши примеры. Так что в [1] я храню все биты, которые делают это.

Выход:

['national news', 'call to end affordable care act is immoral says cha president']
['new website puts louisiana art on businesses walls']
['global clean energy inc otcpkgcei climbs investors radar as key momentum reading hits 456 69429']
['BP General+News', 'female music art to take center stage at swan day in new britain']
['Trump orders Treasury HUD to develop new plan 13721842.php']
['research delivers insight into the global business voip services market during the period 2018 2025']
['why mirza international limited nse 233259149.html']
['indian gaming industry grows in revenues.asp']
['facebook instagram banning pro white 210002719.html']
['press release', 'fluence receives another aspiraltm bulk order with partner itest in china 2019 03 27']
['top firms decry religious exemption bills proposed in texas', 'article_68a5c4d6 2f72 5a6e 8abd 4f04a44ee74f.html']
['correction trump investigations sater lawsuit story', 'article_ed20e441 de30 5b57 aafd b1f7d7929f71.html']
['weather channel sued 125 million over death storm chase collision']

PS. Я думаю, что ваш алгоритм мог бы сделать немного мысли. Проблемы, которые я вижу:

  • более одного бита может содержать дефис, где:
    • оба содержат только слова из словаря (см. Первый и четвертый вывод)
    • один из них "явно" не заголовок (см. Второй и третий снизу)
  • ложные фрагменты строк в конце реального заголовка: например, «13721842.php», «reports.asp», «210002719.html»
  • Необходимо заменить в пробелах символы, отличные от '/', (см. Четвертое, «Общие + Новости»)
1 голос
/ 05 апреля 2019

Вот немного другой вариант, который, кажется, дает хорошие результаты из предоставленных вами образцов.

Из частей с тире мы обрезаем любые конечные шестнадцатеричные строки и расширение имени файла;затем мы извлекаем один из них с наибольшим количеством тире из каждого URL и, наконец, заменяем оставшиеся тире пробелами.

import re

regex = re.compile(r'(-[0-9a-f]+)*(\.[a-z]+)?$', re.IGNORECASE)

for url in urls:
    parts = url.split('/')
    trimmed = [regex.sub('', x) for x in parts if '-' in x]
    longest = sorted(trimmed, key=lambda x: -len(x.split('-')))[0]
    print(longest.replace('-', ' '))

Вывод:

call to end affordable care act is immoral says cha president
new website puts louisiana art on businesses walls
global clean energy inc otcpkgcei climbs investors radar as key momentum reading hits
female music art to take center stage at swan day in new britain
Trump orders Treasury HUD to develop new plan
research delivers insight into the global business voip services market during the period
why mirza international limited nse
indian gaming industry grows in revenues
facebook instagram banning pro white
fluence receives another aspiraltm bulk order with partner itest in china
top firms decry religious exemption bills proposed in texas
correction trump investigations sater lawsuit story
weather channel sued 125 million over death storm chase collision

Моя первоначальная попытка очиститвывести числа с конца URL только после извлечения самого длинного, и это сработало для ваших примеров;но обрезание конечных чисел сразу при расщеплении, вероятно, более устойчиво к изменениям в этих паттернах.

1 голос
/ 05 апреля 2019

Поскольку URL-адреса не соответствуют друг другу, указывается тот факт, что первый и третий URL-адреса имеют другой шаблон, чем остальные.

Использование r.split():

s = ['http://catholicphilly.com/2019/03/news/national-news/call-to-end-affordable-care-act-is-immoral-says-cha-president/',
 'https://www.houmatoday.com/news/20190327/new-website-puts-louisiana-art-on-businesses-walls',
 'https://feltonbusinessnews.com/global-clean-energy-inc-otcpkgcei-climbs-investors-radar-as-key-momentum-reading-hits-456-69429/149601/',
 'http://www.bristolpress.com/BP-General+News/347592/female-music-art-to-take-center-stage-at-swan-day-in-new-britain',
 'https://www.sfgate.com/business/article/Trump-orders-Treasury-HUD-to-develop-new-plan-13721842.php',
 'https://industrytoday.co.uk/it/research-delivers-insight-into-the-global-business-voip-services-market-during-the-period-2018-2025',
 'https://news.yahoo.com/why-mirza-international-limited-nse-233259149.html',
 'https://www.indianz.com/IndianGaming/2019/03/27/indian-gaming-industry-grows-in-revenues.asp',
 'https://www.yahoo.com/entertainment/facebook-instagram-banning-pro-white-210002719.html',
 'https://www.marketwatch.com/press-release/fluence-receives-another-aspiraltm-bulk-order-with-partner-itest-in-china-2019-03-27',
 'https://www.valleymorningstar.com/news/elections/top-firms-decry-religious-exemption-bills-proposed-in-texas/article_68a5c4d6-2f72-5a6e-8abd-4f04a44ee74f.html',
 'https://tucson.com/news/national/correction-trump-investigations-sater-lawsuit-story/article_ed20e441-de30-5b57-aafd-b1f7d7929f71.html',
 'https://www.publicradiotulsa.org/post/weather-channel-sued-125-million-over-death-storm-chase-collision']



for url in s:
  url = url.replace("-", " ")
  if url.rsplit('/', 1)[1] == '':   # For case 1 and 3rd url
       if url.rsplit('/', 2)[1].isdigit():   # For 3rd case url
            print(url.rsplit('/', 3)[1])
       else:
           print(url.rsplit('/', 2)[1])
  else:
       print(url.rsplit('/', 1)[1])   # except 1st and 3rd case urls

OUTPUT

call to end affordable care act is immoral says cha president
new website puts louisiana art on businesses walls
global clean energy inc otcpkgcei climbs investors radar as key momentum reading hits 456 69429
female music art to take center stage at swan day in new britain
Trump orders Treasury HUD to develop new plan 13721842.php
research delivers insight into the global business voip services market during the period 2018 2025
why mirza international limited nse 233259149.html
indian gaming industry grows in revenues.asp
facebook instagram banning pro white 210002719.html
fluence receives another aspiraltm bulk order with partner itest in china 2019 03 27
article_68a5c4d6 2f72 5a6e 8abd 4f04a44ee74f.html
article_ed20e441 de30 5b57 aafd b1f7d7929f71.html
weather channel sued 125 million over death storm chase collision
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...