Использование регулярных выражений в Python для получения нескольких повторяющихся строк - PullRequest
0 голосов
/ 24 марта 2019

Я очень плохо знаком с RegEx и у меня очень большой текстовый файл, небольшая часть которого показана ниже:

<div class="hbk-preamble " id="preamble-APG5180">
<div class="hbk-preamble-entry">
<div class="hbk-preamble-icon hbk-preamble-icon_mode"></div>
<p class="hbk-preamble-heading">Offered</p>
<p><a href="index-bylocation-city-melbourne.html">City (Melbourne)</a></p><ul class="hbk-preamble-list__offerings"><li>Summer semester A 2019 (Flexible)</li></ul><p><a href="index-bylocation-clayton.html">Clayton</a></p><ul class="hbk-preamble-list__offerings"><li>First semester 2019 (On-campus)</li></ul>
</div>
</div>
<div class="notes">
<p class="hbk-heading hdg_6">Notes</p>
<p></p><ul>
<li>The unit may be offered as part of the <a class="hbk-screen-url" href="http://www.monash.edu/students/courses/arts/summer-program.html">Summer Arts Program</a><span class="hbk-print-url">Summer Arts Program (<a href="http://www.monash.edu/students/courses/arts/summer-program.html">http://www.monash.edu/students/courses/arts/summer-program.html</a>)</span>.</li>
<li>For more information please visit the <a class="hbk-screen-url" href="https://www.anzsog.edu.au/">ANZSOG webpage</a><span class="hbk-print-url">ANZSOG webpage (<a href="https://www.anzsog.edu.au/">https://www.anzsog.edu.au/</a>)</span>.</li>
</ul>
</div>
<h2 class="hbk-heading">Synopsis</h2>
<div>
<p>The media is one of the most important components of any political society. In a liberal democracy like Australia, its role and function have profound implications for the conduct of politics, the nature of democracy and public policy outcomes. In this unit, the relationship between the media, politics and public policy is studied from three broad perspectives. First, the politics of the media is investigated from the perspective of liberal democratic theory in order to understand the role of news media on the policy debate. Second, the political economy of the media is investigated. Particular emphasis is on the structure and operation of media organisations and journalists and how political news is covered. Third, the unit undertakes a study of the relationship between the media and political actors. Particular emphasis is on the use of public relations and 'spin doctors' in managing the media as well as the utilisation of political advertising and strategic political communication by governments and political agents.</p>
</div>
<h2 class="hbk-heading">Outcomes</h2>
<div>
<p>Upon successful completion of the unit students should have:</p>
<ol princestart="0" start="1" type="1">

Я бы хотел использовать RegEx, чтобы получить из него только текст «Синопсис»:

The media is one of the most important components of any political society. In a liberal democracy like Australia, its role and function have profound implications for the conduct of politics, the nature of democracy and public policy outcomes. In this unit, the relationship between the media, politics and public policy is studied from three broad perspectives. First, the politics of the media is investigated from the perspective of liberal democratic theory in order to understand the role of news media on the policy debate. Second, the political economy of the media is investigated. Particular emphasis is on the structure and operation of media organisations and journalists and how political news is covered. Third, the unit undertakes a study of the relationship between the media and political actors. Particular emphasis is on the use of public relations and 'spin doctors' in managing the media as well as the utilisation of political advertising and strategic political communication by governments and political agents.

Мне нужен текст для каждого раздела в текстовом файле, что мне делать?

До сих пор я читал в своем текстовом файле, используя read и readlines, но я не могу установить шаблон для начала.

Ответы [ 2 ]

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

Я бы порекомендовал пакет Beautifulsoup, чтобы сделать это. Вы можете попробовать что-то вроде этого:

import requests
from bs4 import BeautifulSoup
data = requests.get('put website address here')
soup = BeautifulSoup(data.text, 'html.parser')
for i in soup.find_all('h2', {'class':'hbk-heading'}):
    print(i.text.strip())
1 голос
/ 24 марта 2019

Я начну с того, что не отвечу на ваш вопрос напрямую.Я предполагаю, что ваш вопрос XY проблема .В вашем случае вам приходится иметь дело с HTML, поэтому у вас есть множество мощных инструментов, созданных для этого.

Взгляните на BeautifulSoup для Python:

from bs4 import BeautifulSoup
soup = BeautifulSoup(content, 'html.parser')

Из этого soup вы можете извлечь все, что вам нужно.

Теперь из вашего вопроса, если вы все ещеВы хотите использовать регулярные выражения, которые вы можете использовать https://regex101.com, чтобы помочь вам:

Демо: https://regex101.com/r/AcozoW/1

<p.*?Notes.*?<li>(.+?)<\/li>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...