Напишите функцию, которая принимает текст и возвращает словарь, где ключами являются слова из текста, а значениями — список индексов строк, в которых эти слова встречаются.
Пример:
text = """Python is great.
JavaScript is also great.
Python is popular."""
result = word_index(text)
print(result)
# Ожидаемый результат:
# {
# 'python': [0, 2],
# 'is': [0, 1, 2],
# 'great': [0, 1],
# 'javascript': [1],
# 'also': [1],
# 'popular': [2]
# }
Решение задачи🔽
def word_index(text):
from collections import defaultdict
import re
index = defaultdict(list)
lines = text.splitlines()
for i, line in enumerate(lines):
words = re.findall(r'\b\w+\b', line.lower())
for word in words:
if i not in index[word]:
index[word].append(i)
return dict(index)
# Пример использования:
text = """Python is great.
JavaScript is also great.
Python is popular."""
result = word_index(text)
print(result)