Как получить первое слово каждого элемента в спиcке, используя только модуль re
У меня есть определенный лист с книгами, нужно добыть из каждого элемента в книге(тоесть названия книги) первое слово используя только модуль re
text = [
"1984, by George Orwell",
"Harry Potter and the Philosopher’s Stone, by J.K. Rowling",
"The Lord of the Rings, by J.R.R. Tolkien",
"The Great Gatsby, by F. Scott Fitzgerald",
"Pride and Prejudice, by Jane Austen",
"The Hobbit, by J.R.R. Tolkien",
"Little Women, by Louisa May Alcott",
"Fahrenheit 451, by Ray Bradbury",
"Jane Eyre, by Charlotte Bronte",
"Animal Farm, by George Orwell",
"Gone with the Wind, by Margaret Mitchell"
]
Ответы (1 шт):
Автор решения: ZxNuClear
→ Ссылка
import re
text = [
"1984, by George Orwell",
"Harry Potter and the Philosopher’s Stone, by J.K. Rowling",
"The Lord of the Rings, by J.R.R. Tolkien",
"The Great Gatsby, by F. Scott Fitzgerald",
"Pride and Prejudice, by Jane Austen",
"The Hobbit, by J.R.R. Tolkien",
"Little Women, by Louisa May Alcott",
"Fahrenheit 451, by Ray Bradbury",
"Jane Eyre, by Charlotte Bronte",
"Animal Farm, by George Orwell",
"Gone with the Wind, by Margaret Mitchell"
]
for x in text:
word = re.findall(r'\w+', x)[0]
print(word)
или
word = [ re.findall(r'\w+', x)[0] for x in text ]
print(word)
Стоит понимать, что в случае таких названий как The Lord..., The Hobbit... и т.д. результатом будет The