1

Тема: AHK: API Типографа Лебедева

Привет, форумчане.

Я хочу создать скрипт, который будет типографить выделенный текст. Для этого думаю подключаться к типографу Лебедева.
Подскажите, как это сделать вообще? И можно ли вообще?

Типограф: http://www.artlebedev.ru/tools/typograf/

API: http://www.artlebedev.ru/tools/typograf/webservice/

2

Re: AHK: API Типографа Лебедева

Вроде получилось:

text1 := "Johnson & Johnson"
text2 =
(
— Это "Типограф"?
— Нет, это «Типограф»!
)
Typograf := new Typograf
MsgBox, % Typograf.Process(text1)
MsgBox, % Typograf.Process(text2)
MsgBox, % Typograf.Process(text2, true)  ; с переносом строк

class Typograf  {
   __New()  {
      this.xmlhttp := ComObjCreate("Msxml2.XMLHTTP")
      this.WaitForResponse := ObjBindMethod(this, "Ready")
   }
   
   Process(text, useBr := false)  {
      text := this.Replace(text)
      xmlRequest := "<?xml version=""1.0"" encoding=""UTF-8""?>"
                  . "<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"""
                  . " xmlns:xsd=""http://www.w3.org/2001/XMLSchema"""
                  . " xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">"
                  . "<soap:Body>"
                  . "<ProcessText xmlns=""http://typograf.artlebedev.ru/webservices/"">"
                  . "<text>" . text . "</text>"
                  . "<useP>0</useP>"
                  . "<useBr>" . useBr . "</useBr>"
                  . "</ProcessText></soap:Body></soap:Envelope>"
                  
      url := "http://typograf.artlebedev.ru/webservices/typograf.asmx"
      this.xmlhttp.Open("POST", url, true)
      this.xmlhttp.onreadystatechange := this.WaitForResponse
      this.xmlhttp.setRequestHeader("Content-Type", "text/xml")
      this.xmlhttp.Send(xmlRequest)
      while this.result = ""
         Sleep, 200
      res := this.Replace(this.result, false)
      this.result := ""
      Return RegExReplace(res, "s).*<ProcessTextResult>(.*)</ProcessTextResult>.*", "$1")
   }
   
   Ready()  {
      if this.xmlhttp.readyState != 4
         Return
      this.result := this.xmlhttp.ResponseText
   }
   
   Replace(text, direction := true)  {
      for k, v in [ ["&", "&amp;"], ["<", "&lt;"], [">", "&gt;"] ]
         text := StrReplace(text, direction ? v[1] : v[2], direction ? v[2] : v[1])
      Return text
   }
}
Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

3

Re: AHK: API Типографа Лебедева

Нашел 2 ошибки:
1) Это:

Return RegExReplace(res, "s).*<ProcessTextResult>(.*)</ProcessTextResult>.*", "$1")

Надо исправить на это:

Return RegExReplace(res, "s).*?<ProcessTextResult>(.*)</ProcessTextResult>.*", "$1")

2) Нарушена последовательность изменений в функции Replace(text, direction := true).
Ответ нужно парсить  в такой последовательности:

response = response.replace (/&gt;/g, '>');
response = response.replace (/&lt;/g, '<');
response = response.replace (/&amp;/g, '&');

4

Re: AHK: API Типографа Лебедева

1) — не имеет смысла, в ответе только один такой тег.
2) — а какая разница?

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

5

Re: AHK: API Типографа Лебедева

1) Имеет. У тебя часть текста может съесться:

text1 =
(
<ProcessTextResult>
— Это "Типограф"?
<ProcessTextResult>
— Нет, это «Типограф»!
)

2) Разница в результате оттипографивания если делать это через сайт:

text1 =
(
<>
)

6

Re: AHK: API Типографа Лебедева

2) Точно, но достаточно просто перенести замену ["&", "&amp;"] на последнее место.
1) Согласен, но не в этом дело, нужно просто поменять местами замену спецсимволов и поиск тега.

text1 := "<>"
text2 =
(
<ProcessTextResult>
— Это "Типограф"?
<ProcessTextResult>
— Нет, это «Типограф»!
)
Typograf := new Typograf
MsgBox, % Typograf.Process(text1)
MsgBox, % Typograf.Process(text2)
MsgBox, % Typograf.Process(text2, true)  ; с переносом строк

class Typograf  {
   __New()  {
      this.xmlhttp := ComObjCreate("Msxml2.XMLHTTP")
      this.WaitForResponse := ObjBindMethod(this, "Ready")
   }
   
   Process(text, useBr := false)  {
      text := this.Replace(text)
      xmlRequest := "<?xml version=""1.0"" encoding=""UTF-8""?>"
                  . "<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"""
                  . " xmlns:xsd=""http://www.w3.org/2001/XMLSchema"""
                  . " xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">"
                  . "<soap:Body>"
                  . "<ProcessText xmlns=""http://typograf.artlebedev.ru/webservices/"">"
                  . "<text>" . text . "</text>"
                  . "<useP>0</useP>"
                  . "<useBr>" . useBr . "</useBr>"
                  . "</ProcessText></soap:Body></soap:Envelope>"
                  
      url := "http://typograf.artlebedev.ru/webservices/typograf.asmx"
      this.xmlhttp.Open("POST", url, true)
      this.xmlhttp.onreadystatechange := this.WaitForResponse
      this.xmlhttp.setRequestHeader("Content-Type", "text/xml")
      this.xmlhttp.Send(xmlRequest)
      while this.result = ""
         Sleep, 200
      res := RegExReplace(this.result, "s).*<ProcessTextResult>(.*)</ProcessTextResult>.*", "$1")
      this.result := ""
      Return this.Replace(res, false)
   }
   
   Ready()  {
      if this.xmlhttp.readyState != 4
         Return
      this.result := this.xmlhttp.ResponseText
   }
   
   Replace(text, direction := true)  {
      for k, v in [ ["<", "&lt;"], [">", "&gt;"], ["&", "&amp;"] ]
         text := StrReplace(text, direction ? v[1] : v[2], direction ? v[2] : v[1])
      Return text
   }
}
Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

7

Re: AHK: API Типографа Лебедева

Результат по сравнению с сайтом разный:

text2 =
(
<ProcessTextResult>
— Это "Типограф"?
<ProcessTextResult>
— Нет, это «Типограф»!
)

8

Re: AHK: API Типографа Лебедева

Ну в этом случае на сайте ошибка. Угловые скобки должны быть заменены.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

9

Re: AHK: API Типографа Лебедева

Хотя не уверен, надо подумать про последовательность замен.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

10

Re: AHK: API Типографа Лебедева

Ну если посмотреть исходник примера, то там идет так:

function remoteTypograf (text)
{
text = text.replace (/<[^>]+>/g, '');
text = text.replace (/&/g, '&amp;');
text = text.replace (/</g, '&lt;');
text = text.replace (/>/g, '&gt;');
function parseTypografAnswer()
{
var response = xmlSocket.responseText;
var re = /<ProcessTextResult>\s*((.|\n)*?)\s*<\/ProcessTextResult>/m;
response = re.exec (response);
response = RegExp.$1;
response = response.replace (/&gt;/g, '>');
response = response.replace (/&lt;/g, '<');
response = response.replace (/&amp;/g, '&');

http://www.artlebedev.ru/tools/technogr … ample.html

+ Gif

11

Re: AHK: API Типографа Лебедева

Вот так, как на сайте:

text1 := "<>"
text2 =
(
<ProcessTextResult>
— Это "Типограф"?
<ProcessTextResult>
— Нет, это «Типограф»!
)
Typograf := new Typograf
MsgBox, % Typograf.Process(text1)
MsgBox, % Typograf.Process(text2)
MsgBox, % Typograf.Process(text2, true)  ; с переносом строк

class Typograf  {
   __New()  {
      this.xmlhttp := ComObjCreate("Msxml2.XMLHTTP")
      this.WaitForResponse := ObjBindMethod(this, "Ready")
   }
   
   Process(text, useBr := false)  {
      text := this.Replace(text)
      xmlRequest := "<?xml version=""1.0"" encoding=""UTF-8""?>"
                  . "<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"""
                  . " xmlns:xsd=""http://www.w3.org/2001/XMLSchema"""
                  . " xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">"
                  . "<soap:Body>"
                  . "<ProcessText xmlns=""http://typograf.artlebedev.ru/webservices/"">"
                  . "<text>" . text . "</text>"
                  . "<useP>0</useP>"
                  . "<useBr>" . useBr . "</useBr>"
                  . "</ProcessText></soap:Body></soap:Envelope>"
                  
      url := "http://typograf.artlebedev.ru/webservices/typograf.asmx"
      this.xmlhttp.Open("POST", url, true)
      this.xmlhttp.onreadystatechange := this.WaitForResponse
      this.xmlhttp.setRequestHeader("Content-Type", "text/xml")
      this.xmlhttp.Send(xmlRequest)
      while this.result = ""
         Sleep, 200
      res := RegExReplace(this.result, "s).*<ProcessTextResult>(.*)</ProcessTextResult>.*", "$1")
      this.result := ""
      Return this.Replace(res, false)
   }
   
   Ready()  {
      if this.xmlhttp.readyState != 4
         Return
      this.result := this.xmlhttp.ResponseText
   }
   
   Replace(text, direction := true)  {
      for k, v in direction ? [["&", "&amp;"], ["<", "&lt;"], [">", "&gt;"]] : [["&lt;", "<"], ["&gt;", ">"], ["&amp;", "&"]]
         text := StrReplace(text, v[1], v[2])
      Return text
   }
}

Только, если как в примере, тогда то, что в тегах (в угловых скобках), вообще удалится:

text = text.replace (/<[^>]+>/g, '');
Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder
+ Gif

12 (изменено: Gif, 2017-01-04 10:53:29)

Re: AHK: API Типографа Лебедева

Здорово, спасибо большое.

Подскажите еще, как настройки типографа передавать в xml-запросе? Например, чтобы на выходе готовый текст получался, а не буквенные коды.

http://www.artlebedev.ru/tools/typograf/preferences/

Я пока разобрался только как <p></p> и <br> делать.

UPD: уже разобрался. Спасибо еще раз.