Понеділок Міні-Гольф №5: <s> Не </s> НЕ намагайся це зробити вдома


24

Понеділок Міні-Гольф: Серія коротких питань із , розміщена (сподіваємось!) Щопонеділка.

Іноді люди втомлюються життєвими правилами: "не робіть цього", "ви не можете цього зробити", "ми не дозволимо вам це зробити". Це може здатися обмежувальним часом! Але раз у раз добре повеселитися, тож давайте напишемо якийсь код, щоб змінити ці правила. І хоча ми до цього, ми можемо також змінити й інші негативи. (Зрозуміло, ці зміни не стануть лише тимчасовими, тому ми також залишимо оригінальну редакцію.)

Виклик

Ваше завдання полягає в тому, щоб написати програму або функцію, яка розміщує HTML- <s>прориси</s> навколо обмежувальних слів, тобто слів, що закінчуються на n'tабо слідують за ними, notі після кожного з них вставляє свій позитивний еквівалент у ВСІ КАПС. Зрештою, після пробілу слід включити кількість зроблених замін. Наприклад:

Please don't jump into the pool.

стає

Please <s>don't</s> DO jump into the pool. 1

Для слів, що закінчуються n'tабо супроводжуються not(а також cannot), позитивним еквівалентом є все, що стосується вищезгаданого not(виключаючи пробіли). Ось що я маю на увазі:

  • do not speak стає <s>do not</s> DO speak
  • it doesn't work стає it <s>doesn't</s> DOES work
  • we cannot стає we <s>cannot</s> CAN

Однак є кілька винятків. Переконайтесь, що з ними поводиться належним чином.

can't -> <s>can't</s> CAN
won't -> <s>won't</s> WILL
ain't -> <s>ain't</s> AM
shan't -> <s>shan't</s> SHALL
I'm not -> <s>I'm not</s> I AM
you're not -> <s>you're not</s> YOU ARE

Деталі

  • Вхід ніколи не буде містити пробілів, крім звичайних пробілів (немає вкладок, нових рядків тощо).
  • Вхід ніколи не буде містити подвійних негативів (наприклад we can't not do this).
  • Якщо notз’являється одразу після пунктуаційного знака або як частина іншого слова, залиште його.
  • Не забудьте зберегти оригінальний текст, включаючи верхній / нижній регістр, між <s></s>тегами.
  • За бажанням ви можете використовувати <strike></strike>замість <s></s>.

Тестові кейси

Вхідні дані:

I'm sorry, but you can't do that.
Driving on the beach isn't allowed.
Driving on the beach is not allowed.
Please don't jump in; I cannot imagine what might come of that.
Don't worry; we won't get into trouble.
I'm not perfect, but you're not either.
You shan't do it 'cause I ain't doin' it!
Can't we capitalize special cases?
I don't like the words can't, shan't, won't, don't, ain't, or ppcgn't.
Oh, this? It's nothing.
Tie a slipknot in the rope.
Would you like Pinot Noir?
This sentence contains none of the replacement words. Not even knot or ca't.
This sentence doesn't contain one of the replacement words.

Виходи:

I'm sorry, but you <s>can't</s> CAN do that. 1
Driving on the beach <s>isn't</s> IS allowed. 1
Driving on the beach <s>is not</s> IS allowed. 1
Please <s>don't</s> DO jump in; I <s>cannot</s> CAN imagine what might come of that. 2
<s>Don't</s> DO worry; we <s>won't</s> WILL get into trouble. 2
<s>I'm not</s> I AM perfect, but <s>you're not</s> YOU ARE either. 2
You <s>shan't</s> SHALL do it 'cause I <s>ain't</s> AM doin' it! 2
<s>Can't</s> CAN we capitalize special cases? 1
I <s>don't</s> DO like the words <s>can't</s> CAN, <s>shan't</s> SHALL, <s>won't</s> WILL, <s>don't</s> DO, <s>ain't</s> AM, or <s>ppcgn't</s> PPCG. 7
Oh, this? It's nothing. 0
Tie a slipknot in the rope. 0
Would you like Pinot Noir? 0
This sentence contains none of the replacement words. Not even knot or ca't. 0
This sentence <s>doesn't</s> DOES contain one of the replacement words. 1

Оцінка балів

Це , тому найкоротший дійсний код у байтах виграє. Tiebreaker переходить до подання, яке першим дійшло до остаточного підрахунку байтів. Переможець не буде обраний наступного понеділка, 26 жовтня. Удачі!


@FryAmTheEggman Так, якщо немає інших, які варто додати до списку. Я вважаю за краще, але ви маєте якісь пропозиції?
ETHproductions

Ні, просто не хотілося, щоб це страждало від виклику синдрому "ти змінив специфікацію зараз це смокче": P
FryAmTheEggman

1
Пропонований тестовий випадок:Can't we capitalize special cases?
DLosc

Чи потрібно бути обережними з рядками типу: Oh this? It's nothing...або I wonder if we'll notice any words like this??
Дом Гастінгс

2
Один <strike> не </strike> НЕ просто перетворює меми в конкурси!
січня

Відповіді:


7

Піп , 138 140 байт

Так, ця cannot/ knotвідмінність хитра.

x:"ca wo ai sha i'm you're"^sY"CAN0WILL0AM0SHALL0I AM0YOU ARE"^0OqR-`([\w']+)( no|n'|(?<=can)no)t\b`{++i"<s>".a."</s>".s.((yx@?LCb)|UCb)}s.i

Читає рядок від stdin, виводить на stdout. Регекс:

`([\w']+)( no|n'|(?<=can)no)t\b`

відповідає слову (включаючи апострофи), за яким слідує одна з трьох речей:

  • not
  • n't
  • not без пробілу, за умови, що перша половина слова була can

-Оператор на регулярному виразі робить його нечутливим до регістру.

Матчі замінюються результатом наступної функції. (Примітка: у межах функції aє весь збіг і bє група захоплення 1.)

{++i"<s>".a."</s>".s.((yx@?LCb)|UCb)}
 ++i                                   Increment counter
    "<s>".a."</s>"                     Return entire match wrapped in HTML tags...
                  .s.(             )   plus space, plus the following:
                           LCb         Lowercase first capture group
                        x@?            Find its index in list x of special cases (nil if
                                         not in list)
                      (y      )        Use that as index into list y of replacements
                               |UCb    If it wasn't a special case, this is nil, and we
                                         instead use uppercase(b)

Після завершення модифікованого рядка ми також виводимо пробіл та кількість замін i.


3

GNU Sed, 321 байт

(включаючи +1 для -r)

:
s!(can('|no)t)([^<])!<s>\1</s> CAN\3!i
s!(won't)([^<])!<s>\1</s> WILL\2!i
s!(ain't)([^<])!<s>\1</s> AM\2!i
s!(shan't)([^<])!<s>\1</s> SHALL\2!i
s!(I'm not)([^<])!<s>\1</s> I AM\2!i
s!(you're not)([^<])!<s>\1</s> YOU ARE\2!i
t
s!(([^ .!?]+)(n't| not))([^<])!<s>\1</s> \U\2\4!i
t
h
s/1//g
s/<s>/1/g
s/[^1]//g
x
G
s/\n/ /

"Заміна рядків - робота для sed!" Я думав. Але це було напрочуд важко, і я продовжував стикатися із заміною оригінального тексту. І підрахунок! Принаймні, у запитанні немає заборони на унарі ...


2

Perl, 153 байти

150 сценарій + 3 для -p

$c=0|s!\b((ca)nnot|([\w']+)(?: not|n't))\b!"<s>$&</s> ".uc({ai,AM,ca,CAN,wo,WILL,sha,SHALL,"i'm","I AM","you're","YOU ARE"}->{lc$+}||$+)!egi;s/
/ $c
/

Тож поки я співставляю всі тестові випадки зараз, але цей регекс дорого коштував мені ... Я подумаю над цим!

Приклад виводу:

$perl -p can.pl <<< "I'm sorry, but you can't do that.
Driving on the beach isn't allowed.
Driving on the beach is not allowed.
Please don't jump in; I cannot imagine what might come of that.
Don't worry; we won't get into trouble.
I'm not perfect, but you're not either.
You shan't do it 'cause I ain't doin' it!
Can't we capitalize special cases?
I don't like the words can't, shan't, won't, don't, ain't, or ppcgn't.
Oh, this? It's nothing.
This sentence contains none of the replacement words. Not even knot or ca't.
This sentence doesn't contain one of the replacement words.
Tie a slipknot in the rope.
Would you like Pinot Noir?
You cannot be serious\!"
I'm sorry, but you <s>can't</s> CAN do that. 1
Driving on the beach <s>isn't</s> IS allowed. 1
Driving on the beach <s>is not</s> IS allowed. 1
Please <s>don't</s> DO jump in; I <s>cannot</s> CAN imagine what might come of that. 2
<s>Don't</s> DO worry; we <s>won't</s> WILL get into trouble. 2
<s>I'm not</s> I AM perfect, but <s>you're not</s> YOU ARE either. 2
You <s>shan't</s> SHALL do it 'cause I <s>ain't</s> AM doin' it! 2
<s>Can't</s> CAN we capitalize special cases? 1
I <s>don't</s> DO like the words <s>can't</s> CAN, <s>shan't</s> SHALL, <s>won't</s> WILL, <s>don't</s> DO, <s>ain't</s> AM, or <s>ppcgn't</s> PPCG. 7
Oh, this? It's nothing. 0
This sentence contains none of the replacement words. Not even knot or ca't. 0
This sentence <s>doesn't</s> DOES contain one of the replacement words. 1
Tie a slipknot in the rope. 0
Would you like Pinot Noir? 0
You <s>cannot</s> CAN be serious\! 1

Ого, це компактно! Одне питання: I'm notне працює належним чином - це має бути I AMзамість цього I'M. Але я думаю , що вам просто потрібно змінити , I'mщоб i'mв коді , щоб виправити це.
DLosc

Ой - також спробуйте на реченнях, як Tie a slipknot in the rope.або Would you like Pinot Noir?. Їх ще немає у тестових випадках, але наміром ОП було виключити будь-яке слово, що закінчується notокрім cannot.
DLosc

@DLosc Відмінні тестові випадки! Я не міг придумати жодних слів, які закінчуються not! I'mБув поганий промах, спасибі за місце!
Дом Гастінгс
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.