TGViewer
About Python [ru] About Python [ru] @python_tesst · 6.42K subscribers
Post #1670 953
👩‍💻 Обратный индекс слов в тексте

Напишите функцию, которая принимает текст и возвращает словарь, где ключами являются слова из текста, а значениями — список индексов строк, в которых эти слова встречаются.

Пример:

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)
More from @python_tesst
  1. Oct 8, 2026Post #3234
  2. Oct 8, 202650 промптов для ChatGPT, после которых толстенный PDF или статья вовсе не обязательно чита…
  3. Oct 8, 2026Сидишь такой, готовишь стартап на 500M$+, а лимиты сдохли уже на втором запросе. 👉 About…
  4. Oct 8, 2026Post #3231
  5. Oct 7, 2026Python в Cloudflare Workers: всё, теперь по-взрослому — GA Cloudflare перестала держать Py…
  6. Oct 7, 2026Post #3229
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →