Извлечь подстроку из строк в python
Как из текста с рейтингом фильмов извлечь подстроку содержащую рейтинг и название фильма (['9.2 The Shawshank Redemption'], ['9.2 The Godfather'],....
note: for this top 250, only votes from regular voters are considered.
New Distribution Votes Rank Title
0000000125 1888533 9.2 The Shawshank Redemption (1994)
0000000125 1289428 9.2 The Godfather (1972)
0000000124 889607 9.0 The Godfather: Part II (1974)
0000000124 1864164 9.0 The Dark Knight (2008)
0000000133 518449 8.9 12 Angry Men (1957)
Ответы (2 шт):
Автор решения: strawdog
→ Ссылка
import re
a='''
note: for this top 250, only votes from regular voters are considered.
New Distribution Votes Rank Title
0000000125 1888533 9.2 The Shawshank Redemption (1994)
0000000125 1289428 9.2 The Godfather (1972)
0000000124 889607 9.0 The Godfather: Part II (1974)
0000000124 1864164 9.0 The Dark Knight (2008)
0000000133 518449 8.9 12 Angry Men (1957)
'''
res = re.findall(r"(\d+\.\d+\s+.+)\s\(", a)
res:
['9.2 The Shawshank Redemption',
'9.2 The Godfather',
'9.0 The Godfather: Part II',
'9.0 The Dark Knight',
'8.9 12 Angry Men']
Автор решения: максим халяпин
→ Ссылка
Тестировать регулярные выражения можно здесь https://regex101.com
Матчасть https://tproger.ru/translations/regular-expression-python/
Решение:
import re
text = '''note: for this top 250, only votes from regular voters are considered.
New Distribution Votes Rank Title
0000000125 1888533 9.2 The Shawshank Redemption (1994)
0000000125 1289428 9.2 The Godfather (1972)
0000000124 889607 9.0 The Godfather: Part II (1974)
0000000124 1864164 9.0 The Dark Knight (2008)
0000000133 518449 8.9 12 Angry Men (1957)'''
rank_title = re.compile(r'\s{3}(\d+\.\d+\s\s?.+).+\(\d+\)$', re.MULTILINE)
print([list(i.groups()) for i in rank_title.finditer(text)])