تخمین مدت زمان خوانده شدن یک مطلب
نویسنده: وحید نصیری
تاریخ: ۱۳۹۴/۰۵/۱۹ ۱۷:۱۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
var words = text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
return words.Length;
[TestMethod]
public void TestInvalidChars()
{
const string data = "To be . ! < > ( ) ! ! , ; : ' ? + -";
Assert.AreEqual(2, data.WordsCount());
} var words = text.Split(
new[] { ' ', ',', ';', '.', '!', '"', '(', ')', '?', ':', '\'', '«' , '»', '+', '-' },
StringSplitOptions.RemoveEmptyEntries);
return words.Length; [TestMethod]
public void TestSimpleHtmlSpacesWithNewLine()
{
const string data = "<b>this is a test.</b>\n\r<b>this is a test.</b>";
Assert.AreEqual(8, data.WordsCount());
} using System;
using System.Text.RegularExpressions;
namespace ReadingTime
{
public static class CalculateWordsCount
{
private static readonly Regex _matchAllTags =
new Regex(@"<(.|\n)*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static int WordsCount(this string text)
{
if (string.IsNullOrWhiteSpace(text))
{
return 0;
}
text = text.cleanTags().Trim();
text = text.Replace("\t", " ");
text = text.Replace("\n", " ");
text = text.Replace("\r", " ");
var words = text.Split(
new[] { ' ', ',', ';', '.', '!', '"', '(', ')', '?', ':', '\'', '«' , '»', '+', '-' },
StringSplitOptions.RemoveEmptyEntries);
return words.Length;
}
private static string cleanTags(this string data)
{
return data.Replace("\n", "\n ").removeHtmlTags();
}
private static string removeHtmlTags(this string text)
{
return string.IsNullOrEmpty(text) ?
string.Empty :
_matchAllTags.Replace(text, " ").Replace(" ", " ");
}
}
} using System;
namespace ReadingTime
{
public static class CalculateReadingTime
{
public static string MinReadTime(this string text, int wordsPerMinute = 180)
{
var wordsCount = text.WordsCount();
var minutes = wordsCount / wordsPerMinute;
return minutes == 0 ? "کمتر از یک دقیقه" : TimeSpan.FromMinutes(minutes).toReadableString();
}
private static string toReadableString(this TimeSpan span)
{
var formatted = string.Format("{0}{1}{2}{3}",
span.Duration().Days > 0 ? string.Format("{0:0} روز و ", span.Days) : string.Empty,
span.Duration().Hours > 0 ? string.Format("{0:0} ساعت و ", span.Hours) : string.Empty,
span.Duration().Minutes > 0 ? string.Format("{0:0} دقیقه و ", span.Minutes) : string.Empty,
span.Duration().Seconds > 0 ? string.Format("{0:0} ثانیه", span.Seconds) : string.Empty);
if (formatted.EndsWith("و "))
{
formatted = formatted.Substring(0, formatted.Length - 2);
}
if (string.IsNullOrEmpty(formatted))
{
formatted = "0 ثانیه";
}
return formatted.Trim();
}
}
}