С Новым годом! Форум программистов, компьютерный форум, киберфорум
Python для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.91/11: Рейтинг темы: голосов - 11, средняя оценка - 4.91
0 / 0 / 0
Регистрация: 06.08.2022
Сообщений: 42

Выведите САМОЕ короткое слово, которое в тексте встречается чаще всего

20.08.2022, 11:57. Показов 2310. Ответов 5
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Дан текст. Выведите САМОЕ короткое слово, которое в этом тексте встречается чаще всего.

Далее после нахождения такого слова

превратите все его буквы в большие и замените все эти слова в строке (в изначальной) на него(на самое короткое частовстречаемое слово которое написано с больших букв):


Death there mirth way the noisy merit. Piqued shy spring nor six though mutual living ask extent. Replying of dashwood advanced ladyship smallest disposal or. Attempt offices own improve now see. Called person are around county talked her esteem. Those fully these way nay thing seems.
At distant inhabit amongst by. Appetite welcomed interest the goodness boy not. Estimable education for disposing pronounce her. John size good gay plan sent old roof own. Inquietude saw understood his friendship frequently yet. Nature his marked ham wished.
Marianne or husbands if at stronger ye. Considered is as middletons uncommonly. Promotion perfectly ye consisted so. His chatty dining for effect ladies active. Equally journey wishing not several behaved chapter she two sir. Deficient procuring favourite extensive you two. Yet diminution she impossible understood age.
So if on advanced addition absolute received replying throwing he. Delighted consisted newspaper of unfeeling as neglected so. Tell size come hard mrs and four fond are. Of in commanded earnestly resources it. At quitting in strictly up wandered of relation answered felicity. Side need at in what dear ever upon if. Same down want joy neat ask pain help she. Alone three stuff use law walls fat asked. Near do that he help.
Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other.
Consulted he eagerness unfeeling deficient existence of. Calling nothing end fertile for venture way boy. Esteem spirit temper too say adieus who direct esteem. It esteems luckily mr or picture placing drawing no. Apartments frequently or motionless on reasonable projecting expression. Way mrs end gave tall walk fact bed.
Offered say visited elderly and. Waited period are played family man formed. He ye body or made on pain part meet. You one delay nor begin our folly abode. By disposed replying mr me unpacked no. As moonlight of my resolving unwilling.
Folly words widow one downs few age every seven. If miss part by fact he park just shew. Discovered had get considered projection who favourable. Necessary up knowledge it tolerably. Unwilling departure education is be dashwoods or an. Use off agreeable law unwilling sir deficient curiosity instantly. Easy mind life fact with see has bore ten. Parish any chatty can elinor direct for former. Up as meant widow equal an share least.
With my them if up many. Lain week nay she them her she. Extremity so attending objection as engrossed gentleman something. Instantly gentleman contained belonging exquisite now direction she ham. West room at sent if year. Numerous indulged distance old law you. Total state as merit court green decay he. Steepest sex bachelor the may delicate its yourself. As he instantly on discovery concluded to. Open draw far pure miss felt say yet few sigh.
Out too the been like hard off. Improve enquire welcome own beloved matters her. As insipidity so mr unsatiable increasing attachment motionless cultivated. Addition mr husbands unpacked occasion he oh. Is unsatiable if projecting boisterous insensible. It recommend be resolving pretended middleton.
0
Лучшие ответы (1)
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
20.08.2022, 11:57
Ответы с готовыми решениями:

Выведите слово, которое в тексте встречается чаще всего
Здравствуйте! На онлайн-курсах получил вот такую задачу: Дан текст. Выведите слово, которое в этом тексте встречается чаще всего....

Вывести на экран слово, которое встречается в тексте чаще всего
Дан текст, состоящий из количества строк текста и самого текста. Вывести на экран слово, которое встречается в тексте чаще всего. Для...

Найти слово в списке, которое встречается чаще всего
Здравствуйте. Полностью задача звучит так: Дан текст: в первой строке задано число строк, далее идут сами строки. Выведите слово,...

5
96 / 64 / 34
Регистрация: 08.02.2021
Сообщений: 213
20.08.2022, 22:35
Не самое оптимальное решение, но
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
string = 'Ваша строка...'
# сделаем список из строки (для удобства итерации)
lst = string.split()
# пустой словарь, в котором будут храниться самые короткие слова
short_words = {}
# определяем минимальную длину слова в нашем тексте
min_length = min([len(word) for word in lst])
# добавляем в наш словарь данные: короткое слово и сколько раз оно встречается
for word in lst:
    if len(word) == min_length:
        if word.lower() not in short_words:
            short_words[word.lower()] = 1
        else:
            short_words[word.lower()] += 1
# сортируем словарь и берем самое часто встречаемое слово
shortest_word = sorted(short_words, key=short_words.get)[-1]
print(f'Самое короткое слово, которое встречается чаще всего - "{shortest_word}", {short_words[shortest_word]} раз(а)')
# выполняем замену самого короткого слова на то же слово, только в верхнем регистре
for index, word in enumerate(lst):
    if word.lower() == shortest_word:
        lst[index] = shortest_word.upper()
# собираем все обратно в строку        
string = ' '.join(lst)
1
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7390 / 4817 / 1246
Регистрация: 30.03.2015
Сообщений: 13,664
Записей в блоге: 29
21.08.2022, 09:40
Лучший ответ Сообщение было отмечено mik-a-el как решение

Решение

Fun_lola,
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from collections import Counter
text = '''Death there mirth way the noisy merit. Piqued shy spring nor six though mutual living ask extent. Replying of dashwood advanced ladyship smallest disposal or. Attempt offices own improve now see. Called person are around county talked her esteem. Those fully these way nay thing seems.
At distant inhabit amongst by. Appetite welcomed interest the goodness boy not. Estimable education for disposing pronounce her. John size good gay plan sent old roof own. Inquietude saw understood his friendship frequently yet. Nature his marked ham wished.
Marianne or husbands if at stronger ye. Considered is as middletons uncommonly. Promotion perfectly ye consisted so. His chatty dining for effect ladies active. Equally journey wishing not several behaved chapter she two sir. Deficient procuring favourite extensive you two. Yet diminution she impossible understood age.
So if on advanced addition absolute received replying throwing he. Delighted consisted newspaper of unfeeling as neglected so. Tell size come hard mrs and four fond are. Of in commanded earnestly resources it. At quitting in strictly up wandered of relation answered felicity. Side need at in what dear ever upon if. Same down want joy neat ask pain help she. Alone three stuff use law walls fat asked. Near do that he help.
Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other.
Consulted he eagerness unfeeling deficient existence of. Calling nothing end fertile for venture way boy. Esteem spirit temper too say adieus who direct esteem. It esteems luckily mr or picture placing drawing no. Apartments frequently or motionless on reasonable projecting expression. Way mrs end gave tall walk fact bed.
Offered say visited elderly and. Waited period are played family man formed. He ye body or made on pain part meet. You one delay nor begin our folly abode. By disposed replying mr me unpacked no. As moonlight of my resolving unwilling.
Folly words widow one downs few age every seven. If miss part by fact he park just shew. Discovered had get considered projection who favourable. Necessary up knowledge it tolerably. Unwilling departure education is be dashwoods or an. Use off agreeable law unwilling sir deficient curiosity instantly. Easy mind life fact with see has bore ten. Parish any chatty can elinor direct for former. Up as meant widow equal an share least.
With my them if up many. Lain week nay she them her she. Extremity so attending objection as engrossed gentleman something. Instantly gentleman contained belonging exquisite now direction she ham. West room at sent if year. Numerous indulged distance old law you. Total state as merit court green decay he. Steepest sex bachelor the may delicate its yourself. As he instantly on discovery concluded to. Open draw far pure miss felt say yet few sigh.
Out too the been like hard off. Improve enquire welcome own beloved matters her. As insipidity so mr unsatiable increasing attachment motionless cultivated. Addition mr husbands unpacked occasion he oh. Is unsatiable if projecting boisterous insensible. It recommend be resolving pretended middleton.'''
 
words = [word.strip() for word in text.split()]
lower_words = [word.lower() for word in words]
counter = Counter(lower_words)
minimal = sorted(counter.most_common(), key=lambda x: len(x[0]))
common_shortest = minimal[0][0]
for word in words:
    if word.lower().strip() == common_shortest:
        text = text.replace(f' {word} ', f' {common_shortest.upper()} ')
 
print(text)
результат
Code
1
2
3
4
5
6
7
8
9
10
Death there mirth way the noisy merit. Piqued shy spring nor six though mutual living ask extent. Replying of dashwood advanced ladyship smallest disposal or. Attempt offices own improve now see. Called person are around county talked her esteem. Those fully these way nay thing seems.
At distant inhabit amongst by. Appetite welcomed interest the goodness boy not. Estimable education for disposing pronounce her. John size good gay plan sent old roof own. Inquietude saw understood his friendship frequently yet. Nature his marked ham wished.
Marianne or husbands if at stronger ye. Considered is AS middletons uncommonly. Promotion perfectly ye consisted so. His chatty dining for effect ladies active. Equally journey wishing not several behaved chapter she two sir. Deficient procuring favourite extensive you two. Yet diminution she impossible understood age.
So if on advanced addition absolute received replying throwing he. Delighted consisted newspaper of unfeeling AS neglected so. Tell size come hard mrs and four fond are. Of in commanded earnestly resources it. At quitting in strictly up wandered of relation answered felicity. Side need at in what dear ever upon if. Same down want joy neat ask pain help she. Alone three stuff use law walls fat asked. Near do that he help.
Betrayed cheerful declared end and. Questions we additions is extremely incommode. Next half add call them eat face. Age lived smile six defer bed their few. Had admitting concluded too behaviour him she. Of death to or to being other.
Consulted he eagerness unfeeling deficient existence of. Calling nothing end fertile for venture way boy. Esteem spirit temper too say adieus who direct esteem. It esteems luckily mr or picture placing drawing no. Apartments frequently or motionless on reasonable projecting expression. Way mrs end gave tall walk fact bed.
Offered say visited elderly and. Waited period are played family man formed. He ye body or made on pain part meet. You one delay nor begin our folly abode. By disposed replying mr me unpacked no. AS moonlight of my resolving unwilling.
Folly words widow one downs few age every seven. If miss part by fact he park just shew. Discovered had get considered projection who favourable. Necessary up knowledge it tolerably. Unwilling departure education is be dashwoods or an. Use off agreeable law unwilling sir deficient curiosity instantly. Easy mind life fact with see has bore ten. Parish any chatty can elinor direct for former. Up AS meant widow equal an share least.
With my them if up many. Lain week nay she them her she. Extremity so attending objection AS engrossed gentleman something. Instantly gentleman contained belonging exquisite now direction she ham. West room at sent if year. Numerous indulged distance old law you. Total state AS merit court green decay he. Steepest sex bachelor the may delicate its yourself. AS he instantly on discovery concluded to. Open draw far pure miss felt say yet few sigh.
Out too the been like hard off. Improve enquire welcome own beloved matters her. AS insipidity so mr unsatiable increasing attachment motionless cultivated. Addition mr husbands unpacked occasion he oh. Is unsatiable if projecting boisterous insensible. It recommend be resolving pretended middleton.
2
0 / 0 / 0
Регистрация: 06.08.2022
Сообщений: 42
21.08.2022, 10:51  [ТС]
Спасибо вам всем
0
5515 / 2868 / 571
Регистрация: 07.11.2019
Сообщений: 4,758
21.08.2022, 12:40
Welemir1, по-моему, можно также без сортировки списка.. :
Python
1
common_shortest = min(counter.most_common(), key=lambda x: len(x[0]))[0]
0
Автоматизируй это!
Эксперт Python
 Аватар для Welemir1
7390 / 4817 / 1246
Регистрация: 30.03.2015
Сообщений: 13,664
Записей в блоге: 29
21.08.2022, 15:46
u235, возможно, это я перестраховался, вдруг был бы артикль "а" где то, он короче as
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
21.08.2022, 15:46
Помогаю со студенческими работами здесь

Вывести слово которое встречается чаще всего
Задача №2 1. Сами вводим предложение на любом языке 2. Вывести слово которое встречается чаще всего

Выведи слово, которое чаще остальных встречается в тексте
Пользователь вводит текст. Выведи слово, которое чаще остальных встречается в тексте. Нужно выполнить данную задачу используя словари.

С помощью хэш-таблиц выведите слово, которое в тексте встречается чаще всего
Решить с помощью хэш-таблиц! Дан текст (строк может быть много). Выведите слово, которое в этом тексте встречается чаще всего. Если...

Подсчитать сколько раз в тексте встречается каждое слово и удалить то слово, которое встречается чаще всего
Само задание : Вводим текст и для каждого из слов указать, сколько раз оно встречается в тексте. Слово, чаще всего встречающееся в тексте,...

Вывести слово,которое в этом тексте встречается чаще всего
Дан текст (строк может быть много). Выведите слово, которое в этом тексте встречается чаще всего, и количество его повторений в тексте....


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Новые блоги и статьи
изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru