Найти весь год в определенной части текстового файла - PullRequest
0 голосов
/ 11 марта 2019

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

Вот что я получил.

for line in infile_1:
    if '[edit]Crime' in line:
    print(re.findall(r'\d{4}',line[1:]))
    for i in infile_1:
        if '[edit]Education' in infile:
              break

Это только пустая скобка. Это неправильно.

Текст:

[edit]Crime
Main articles: Crime in Chicago and Organized crime in Chicago
Murders in the city peaked first in 1974, with 970 murders when the city's population was over 3 million people (resulting in a murder rate of around 29 per 100,000), and again in 1992 with 943 murders, resulting in a murder rate of 34 per 100,000.[114] Chicago, along with other major US cities, experienced a significant reduction in violent crime rates through the 1990s, eventually recording 448 homicides in 2004, the lowest total since 1965 (15.65 per 100,000.) Chicago's homicide tally remained steady throughout 2005, 2006, and 2007 with 449, 452, and 435 respectively.

In 2008, murders rebounded to 510, 2nd highest in the country (though not in per capita rate), breaking 500 for the first time since 2003.[115][116] For 2009 the murder count was down about 10% for the year, to 458.[117]

2010 saw Chicago's murder rate at its lowest levels since 1965. Overall, 435 homicides were recorded for the year, a 5% decrease from 2009.[118]

1 Ответ

0 голосов
/ 11 марта 2019

Вы можете удалить [edit]Education деталь, разбив текст, а затем отметив [edit]Crime section:

import re
with open('file.txt') as f:
    data = f.read().split('[edit]Crime')[1].split('[edit]')[0]
years = re.findall('(\d\d\d\d)', data)

Вывод:

['1974']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...