gpt4 book ai didi

javascript - 在html文件中将阿拉伯数字转换为阿拉伯/波斯数字

转载 作者:行者123 更新时间:2023-11-29 14:57:56 24 4
gpt4 key购买 nike

我正在尝试将纯文本阿拉伯数字转换为东方阿拉伯数字。所以基本上采用 1 2 3... 并将它们转换为 ١ ٢ ٣ ...。该函数转换所有 数字,包括标签中包含的任何数字,即 H1

 private void LoadHtmlFile(object sender, EventArgs e)
{
var htmlfile = "<html><body><h1>i was born in 1988</h1></body></html>".ToArabicNumber(); ;
webBrowser1.DocumentText=htmlfile;
}


}
public static class StringHelper
{
public static string ToArabicNumber(this string str)
{
if (string.IsNullOrEmpty(str)) return "";
char[] chars;
chars = str.ToCharArray();
for (int i = 0; i < str.Length; i++)
{
if (str[i] >= '0' && str[i] <= '9')
{
chars[i] += (char)1728;
}
}
return new string(chars);
}
}

我也试过在 InnerText 中只定位数字,但它也没有用。下面的代码也会更改标签号。

private void LoadHtmlFile(object sender, EventArgs e)
{
var htmlfile = "<html><body><h1>i was born in 1988</h1></body></html>" ;
webBrowser1.DocumentText=htmlfile;
}

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Body.InnerText = webBrowser1.Document.Body.InnerText.ToArabicNumber();
}

有什么建议吗?

最佳答案

您可以使用正则表达式查找 HTML 中“>”和“<”字符之间的部分,并对这些部分进行操作。这将阻止代码处理标签名称和属性(样式等)。

// Convert all English digits in a string to Arabic digit equivalents
public static string ToArabicNums(string src)
{
const string digits = "۰۱۲۳۴۵۶۷۸۹";
return string.Join("",
src.Select(c => c >= '0' && c <= '9' ? digits[((int)c - (int)'0')] : c)
);
}

// Convert all English digits in the text segments of an HTML
// document to Arabic digit equivalents
public static string ToArabicNumsHtml(string src)
{
string res = src;

Regex re = new Regex(@">(.*?)<");

// get Regex matches
MatchCollection matches = re.Matches(res);

// process in reverse in case transformation function returns
// a string of a different length
for (int i = matches.Count - 1; i >= 0; --i)
{
Match nxt = matches[i];
if (nxt.Groups.Count == 2 && nxt.Groups[1].Length > 0)
{
Group g = nxt.Groups[1];
res = res.Substring(0, g.Index) + ToArabicNums(g.Value) +
res.Substring(g.Index + g.Length);
}

return res;
}

这并不完美,因为它根本不检查标签之外的 HTML 字符说明符,例如结构 &#<digits>; (&#1777; 对于 1 等)通过 Unicode 值指定一个字符,并将替换其中的数字。它也不会处理第一个标签之前或最后一个标签之后的任何额外文本。

示例:

Calling: ToArabicNumsHtml("<html><body><h1>I was born in 1988</h1></body></html>")
Result: "<html><body><h1>I was born in ۱۹۸۸</h1></body></html>"

ToArabicNums 中使用您喜欢的任何代码进行实际的转换,或通过传递转换函数来概括它。

关于javascript - 在html文件中将阿拉伯数字转换为阿拉伯/波斯数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14868380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com