Лучший способ поиска простой текстовой строки в HTML строке в c#? - PullRequest
0 голосов
/ 09 января 2020

Это строка html:

 string htmlString = "<body lang=\"EN-US\" link=\"blue\" vlink=\"#954F72\"><div class=\"WordSection1\"><p class=\"MsoNormal\">Hi, </p><p class=\"MsoNormal\"><o:p>&nbsp;</o:p></p><p class=\"MsoNormal\"><o:p>&nbsp;</o:p></p><p class=\"MsoNormal\">My name is Gaurav Illness.</p><p class=\"MsoNormal\"><span style=\"color:purple !important\">Today <b>MY&nbsp;&nbsp;&nbsp;&nbsp; relation</b>ship breakdown <span style=\"color:red\">happened?<o:p></o:p></span> </span></p><p class=\"MsoNormal\"><span style=\"color:red\"><o:p>&nbsp;</o:p></span></p><p class=\"MsoNormal\"><span style=\"color:red\">I am Gr</span><span style=\"font-size:15.0pt;color:red;background:yellow;mso-highlight:yellow\">iESh and I</span><span style=\"font-size:15.0pt;color:red\"><o:p></o:p></span></p><p class=\"MsoNormal\"><span style=\"font-size:15.0pt;color:#B4C7E7;mso-style-textfill-fill-color:#B4C7E7;mso-style-textfill-fill-alpha:100.0%\">Am drugger.<o:p></o:p></span></p><p class=\"MsoNormal\"><o:p>&nbsp;</o:p></p><p class=\"MsoNormal\" style=\"line-height:16.5pt\"><span style=\"font-size:10.0pt;font-family:&quot;Arial&quot;,sans-serif;color:#1F497D\">Thanks<span style=\"text-transform:uppercase\">,<o:p></o:p>"

Я извлекаю из нее обычный текст, используя эту функцию:

     private static string extractTextFromHtml(string htmlString)
    {
        // Remove new lines since they are not visible in HTML
        html = html.Replace("\n", " ");

        // Remove tab spaces
        html = html.Replace("\t", " ");

        // Remove multiple white spaces from HTML
        html = Regex.Replace(html, "\\s+", " ");

        // Remove HEAD tag
        html = Regex.Replace(html, "<head.*?</head>", ""
                            , RegexOptions.IgnoreCase | RegexOptions.Singleline);

        // Remove any JavaScript
        html = Regex.Replace(html, "<script.*?</script>", ""
          , RegexOptions.IgnoreCase | RegexOptions.Singleline);

        // Replace special characters like &, <, >, " etc.
        StringBuilder sbHTML = new StringBuilder(html);
        // Note: There are many more special characters, these are just
        // most common. You can add new characters in this arrays if needed
        string[] OldWords = {"&nbsp;", "&amp;", "&quot;", "&lt;", "&gt;", "&reg;", "&copy;", "&bull;", "&trade;"};
        string[] NewWords = { " ", "&", "\"", "<", ">", "®", "©", "•", "™" };
        for (int i = 0; i < OldWords.Length; i++)
        {
            sbHTML.Replace(OldWords[i], NewWords[i]);
        }

        // Check if there are line breaks (<br>) or paragraph (<p>)
        sbHTML.Replace("<br>", "\n<br>");
        sbHTML.Replace("<br ", "\n<br ");
        sbHTML.Replace("<p ", "\n<p ");

        // Finally, remove all HTML tags and return plain text
        return System.Text.RegularExpressions.Regex.Replace(
          sbHTML.ToString(), "<[^>]*>", "");
    }

Эта функция возвращает:

«Привет,

Меня зовут Болезнь Гаурава. Сегодня произошел разрыв МОИХ отношений?

Я Gr iESh и Я - наркотик.

Спасибо»

Теперь я отправляю этот текст в API, который обнаруживает, есть эмоции или нет в этих предложениях. API дает ответ на все предложения, которые являются эмоциональными. Например, API говорит: «Сегодня МОЙ разрыв отношений произошел?» эмоционально Теперь я хочу отметить это предложение фиолетовым цветом в html, для которого мне нужно добавить интервал вокруг предложения. Для этого мне нужно найти начальный и конечный индекс этого предложения в коде html.

Как найти начальный и конечный индексы этого предложения в коде html?

У меня есть код, который дает мне индексы, но я думаю, что это не лучший способ делать. Кто-нибудь может предложить лучший способ? Это мой пример кода:

     public static void findTextInHtml(string htmlCode)
    {
        string textToBeFind = "I am GriESh and IAm drugger.";
        int i = 0;
        int j = 0;
        int startIndex = 0;
        int endIndex = 0;
        bool isHtml = false;
        bool isbeingMatched = false;
        while (i < htmlCode.Length)
        {
            if (htmlCode[i] == '<')
            {
                isHtml = true;
                i++;
                continue;
            }
            if (htmlCode[i] == '>')
            {
                isHtml = false;
                i++;
                continue;
            }
            if (isHtml)
            {
                i++;
                continue;
            }
            if (textToBeFind[j] == htmlCode[i])
            {
                if (!isbeingMatched)
                {
                    startIndex = i;
                }
                isbeingMatched = true;
                j++;
                if (j == textToBeFind.Length)
                {
                    endIndex = i;
                    break;
                }
            }
            else
            {
                isbeingMatched = false;
                j = 0;
            }
            i++;
        }
        AddStartSpan(startIndex, htmlCode);
        AddEndSpan(endIndex, htmlCode);
    }

1 Ответ

0 голосов
/ 09 января 2020

Установите пакет nuget HtmlAgilityPack
Тогда его легко разобрать, как это:

string htmlString = "<p class=\"MsoNormal\"><span style=\"color:red\"><o:p>&nbsp;</o:p></span></p><p class=\"MsoNormal\"><span style=\"color:red\">I am Gr</span><span style=\"font-size:15.0pt;color:red;background:yellow;mso-highlight:yellow\">iESh and I</span><span style=\"font-size:15.0pt;color:red\"><o:p></o:p></span></p><p class=\"MsoNormal\"><span style=\"font-size:15.0pt;color:#B4C7E7;mso-style-textfill-fill-color:#B4C7E7;mso-style-textfill-fill-alpha:100.0%\">Am drugger.<o:p></o:p></span></p>";
var doc = new HtmlDocument();
doc.LoadHtml(htmlString);

var inner = doc.DocumentNode.InnerText.TrimStartString("&nbsp;");
// inner = I am GriESh and IAm drugger.

Чтобы удалить nbsp; в начале InnerText

public static string TrimStartString(this string input, string prefixToRemove,
    StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
    if (input != null && prefixToRemove != null
      && input.StartsWith(prefixToRemove, comparisonType))
    {
        return input.Substring(prefixToRemove.Length);
    }
    else return input;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...