• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Humanizr/Humanizer: Humanizer meets all your .NET needs for manipulating and dis ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

Humanizr/Humanizer

开源软件地址(OpenSource Url):

https://github.com/Humanizr/Humanizer

开源编程语言(OpenSource Language):

C# 100.0%

开源软件介绍(OpenSource Introduction):

Logo

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities. It is part of the .NET Foundation, and operates under their code of conduct. It is licensed under the MIT (an OSI approved license).

Join the chat at https://gitter.im/Humanizr/Humanizer

Table of contents

Install

You can install Humanizer as a nuget package:

English only: Humanizer.Core

All languages: Humanizer

Humanizer is a .NET Standard Class Library with support for .NET Standard 1.0+ (.Net 4.5+, UWP, Xamarin, and .NET Core).

Also Humanizer symbols are source indexed with SourceLink and are included in the package so you can step through Humanizer code while debugging your code.

For pre-release builds, Azure Artifacts feed is available where you can pull down CI packages from the latest codebase. The feed URL is:

  • Humanizer package in Humanizer feed in Azure Artifacts https://pkgs.dev.azure.com/dotnet/Humanizer/_packaging/Humanizer/nuget/v3/index.json

Specify Languages (Optional)

New in Humanizer 2.0 is the option to choose which localization packages you wish to use. You choose which packages based on what NuGet package(s) you install. By default, the main Humanizer 2.0 package installs all supported languages exactly like it does in 1.x. If you're not sure, then just use the main Humanizer package.

Here are the options:

  • All languages: use the main Humanizer package. This pulls in Humanizer.Core and all language packages.
  • English: use the Humanizer.Core package. Only the English language resources will be available
  • Specific languages: Use the language specific packages you'd like. For example for French, use Humanizer.Core.fr. You can include multiple languages by installing however many language packages you want.

The detailed explanation for how this works is in the comments here.

Features

Humanize String

Humanize string extensions allow you turn an otherwise computerized string into a more readable human-friendly one. The foundation of this was set in the BDDfy framework where class names, method names and properties are turned into human readable sentences.

"PascalCaseInputStringIsTurnedIntoSentence".Humanize() => "Pascal case input string is turned into sentence"

"Underscored_input_string_is_turned_into_sentence".Humanize() => "Underscored input string is turned into sentence"

"Underscored_input_String_is_turned_INTO_sentence".Humanize() => "Underscored input String is turned INTO sentence"

Note that a string that contains only upper case letters, and consists only of one word, is always treated as an acronym (regardless of its length). To guarantee that any arbitrary string will always be humanized you must use a transform (see Transform method below):

// acronyms are left intact
"HTML".Humanize() => "HTML"

// any unbroken upper case string is treated as an acronym
"HUMANIZER".Humanize() => "HUMANIZER"
"HUMANIZER".Transform(To.LowerCase, To.TitleCase) => "Humanizer"

You may also specify the desired letter casing:

"CanReturnTitleCase".Humanize(LetterCasing.Title) => "Can Return Title Case"

"Can_return_title_Case".Humanize(LetterCasing.Title) => "Can Return Title Case"

"CanReturnLowerCase".Humanize(LetterCasing.LowerCase) => "can return lower case"

"CanHumanizeIntoUpperCase".Humanize(LetterCasing.AllCaps) => "CAN HUMANIZE INTO UPPER CASE"

The LetterCasing API and the methods accepting it are legacy from V0.2 era and will be deprecated in the future. Instead of that, you can use Transform method explained below.

Dehumanize String

Much like you can humanize a computer friendly into human friendly string you can dehumanize a human friendly string into a computer friendly one:

"Pascal case input string is turned into sentence".Dehumanize() => "PascalCaseInputStringIsTurnedIntoSentence"

Transform String

There is a Transform method that supersedes LetterCasing, ApplyCase and Humanize overloads that accept LetterCasing. Transform method signature is as follows:

string Transform(this string input, params IStringTransformer[] transformers)

And there are some out of the box implementations of IStringTransformer for letter casing:

"Sentence casing".Transform(To.LowerCase) => "sentence casing"
"Sentence casing".Transform(To.SentenceCase) => "Sentence casing"
"Sentence casing".Transform(To.TitleCase) => "Sentence Casing"
"Sentence casing".Transform(To.UpperCase) => "SENTENCE CASING"

LowerCase is a public static property on To class that returns an instance of private ToLowerCase class that implements IStringTransformer and knows how to turn a string into lower case.

The benefit of using Transform and IStringTransformer over ApplyCase and LetterCasing is that LetterCasing is an enum and you're limited to use what's in the framework while IStringTransformer is an interface you can implement in your codebase once and use it with Transform method allowing for easy extension.

Truncate String

You can truncate a string using the Truncate method:

"Long text to truncate".Truncate(10) => "Long text…"

By default the '…' character is used to truncate strings. The advantage of using the '…' character instead of "..." is that the former only takes a single character and thus allows more text to be shown before truncation. If you want, you can also provide your own truncation string:

"Long text to truncate".Truncate(10, "---") => "Long te---"

The default truncation strategy, Truncator.FixedLength, is to truncate the input string to a specific length, including the truncation string length. There are two more truncator strategies available: one for a fixed number of (alpha-numerical) characters and one for a fixed number of words. To use a specific truncator when truncating, the two Truncate methods shown in the previous examples all have an overload that allow you to specify the ITruncator instance to use for the truncation. Here are examples on how to use the three provided truncators:

"Long text to truncate".Truncate(10, Truncator.FixedLength) => "Long text…"
"Long text to truncate".Truncate(10, "---", Truncator.FixedLength) => "Long te---"

"Long text to truncate".Truncate(6, Truncator.FixedNumberOfCharacters) => "Long t…"
"Long text to truncate".Truncate(6, "---", Truncator.FixedNumberOfCharacters) => "Lon---"

"Long text to truncate".Truncate(2, Truncator.FixedNumberOfWords) => "Long text…"
"Long text to truncate".Truncate(2, "---", Truncator.FixedNumberOfWords) => "Long text---"

Note that you can also use create your own truncator by implementing the ITruncator interface.

There is also an option to choose whether to truncate the string from the beginning (TruncateFrom.Left) or the end (TruncateFrom.Right). Default is the right as shown in the examples above. The examples below show how to truncate from the beginning of the string:

"Long text to truncate".Truncate(10, Truncator.FixedLength, TruncateFrom.Left) => "… truncate"
"Long text to truncate".Truncate(10, "---", Truncator.FixedLength, TruncateFrom.Left) => "---runcate"

"Long text to truncate".Truncate(10, Truncator.FixedNumberOfCharacters, TruncateFrom.Left) => "…o truncate"
"Long text to truncate".Truncate(16, "---", Truncator.FixedNumberOfCharacters, TruncateFrom.Left) => "---ext to truncate"

"Long text to truncate".Truncate(2, Truncator.FixedNumberOfWords, TruncateFrom.Left) => "…to truncate"
"Long text to truncate".Truncate(2, "---", Truncator.FixedNumberOfWords, TruncateFrom.Left) => "---to truncate"

Format String

You can format a string using the FormatWith() method:

"To be formatted -> {0}/{1}.".FormatWith(1, "A") => "To be formatted -> 1/A."

This is an extension method based on String.Format, so exact rules applies to it. If format is null, it'll throw ArgumentNullException. If passed a fewer number for arguments, it'll throw String.FormatException exception.

You also can specify the culture to use explicitly as the first parameter for the FormatWith() method:

"{0:N2}".FormatWith(new CultureInfo("ru-RU"), 6666.66) => "6 666,66"

If a culture is not specified, current thread's current culture is used.

Humanize Enums

Calling ToString directly on enum members usually results in less than ideal output for users. The solution to this is usually to use DescriptionAttribute data annotation and then read that at runtime to get a more friendly output. That is a great solution; but more often than not we only need to put some space between words of an enum member - which is what String.Humanize() does well. For an enum like:

public enum EnumUnderTest
{
    [Description("Custom description")]
    MemberWithDescriptionAttribute,
    MemberWithoutDescriptionAttribute,
    ALLCAPITALS
}

You will get:

// DescriptionAttribute is honored
EnumUnderTest.MemberWithDescriptionAttribute.Humanize() => "Custom description"

// In the absence of Description attribute string.Humanizer kicks in
EnumUnderTest.MemberWithoutDescriptionAttribute.Humanize() => "Member without description attribute"

// Of course you can still apply letter casing
EnumUnderTest.MemberWithoutDescriptionAttribute.Humanize().Transform(To.TitleCase) => "Member Without Description Attribute"

You are not limited to DescriptionAttribute for custom description. Any attribute applied on enum members with a string Description property counts. This is to help with platforms with missing DescriptionAttribute and also for allowing subclasses of the DescriptionAttribute.

You can even configure the name of the property of attibute to use as description.

Configurator.EnumDescriptionPropertyLocator = p => p.Name == "Info"

If you need to provide localised descriptions you can use DisplayAttribute data annotation instead.

public enum EnumUnderTest
{
    [Display(Description = "EnumUnderTest_Member", ResourceType = typeof(Project.Resources))]
    Member
}

You will get:

EnumUnderTest.Member.Humanize() => "content" // from Project.Resources found under "EnumUnderTest_Member" resource key

Hopefully this will help avoid littering enums with unnecessary attributes!

Dehumanize Enums

Dehumanizes a string into the Enum it was originally Humanized from! The API looks like:

public static TTargetEnum DehumanizeTo<TTargetEnum>(this string input)

And the usage is:

"Member without description attribute".DehumanizeTo<EnumUnderTest>() => EnumUnderTest.MemberWithoutDescriptionAttribute

And just like the Humanize API it honors the Description attribute. You don't have to provide the casing you provided during humanization: it figures it out.

There is also a non-generic counterpart for when the original Enum is not known at compile time:

public static Enum DehumanizeTo(this string input, Type targetEnum, NoMatch onNoMatch = NoMatch.ThrowsException)

which can be used like:

"Member without description attribute".DehumanizeTo(typeof(EnumUnderTest)) => EnumUnderTest.MemberWithoutDescriptionAttribute

By default both methods throw a NoMatchFoundException when they cannot match the provided input against the target enum. In the non-generic method you can also ask the method to return null by setting the second optional parameter to NoMatch.ReturnsNull.

Humanize DateTime

You can Humanize an instance of DateTime or DateTimeOffset and get back a string telling how far back or forward in time that is:

DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"

DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"

DateTimeOffset.UtcNow.AddHours(1).Humanize() => "an hour from now"

Humanizer supports both local and UTC dates as well as dates with offset (DateTimeOffset). You could also provide the date you want the input date to be compared against. If null, it will use the current date as comparison base. Also, culture to use can be specified explicitly. If it is not, current thread's current UI culture is used. Here is the API signature:

public static string Humanize(this DateTime input, bool utcDate = true, DateTime? dateToCompareAgainst = null, CultureInfo culture = null)
public static string Humanize(this DateTimeOffset input, DateTimeOffset? dateToCompareAgainst = null, CultureInfo culture = null)

Many localizations are available for this method. Here is a few examples:

// In ar culture
DateTime.UtcNow.AddDays(-1).Humanize() => "أمس"
DateTime.UtcNow.AddDays(-2).Humanize() => "منذ يومين"
DateTime.UtcNow.AddDays(-3).Humanize() => "منذ 3 أيام"
DateTime.UtcNow.AddDays(-11).Humanize() => "منذ 11 يوم"

// In ru-RU culture
DateTime.UtcNow.AddMinutes(-1).Humanize() => "минуту назад"
DateTime.UtcNow.AddMinutes(-2).Humanize() => "2 минуты назад"
DateTime.UtcNow.AddMinutes(-10).Humanize() => "10 минут назад"
DateTime.UtcNow.AddMinutes(-21).Humanize() => "21 минуту назад"
DateTime.UtcNow.AddMinutes(-22).Humanize() => "22 минуты назад"
DateTime.UtcNow.AddMinutes(-40).Humanize() => "40 минут назад"

There are two strategies for DateTime.Humanize: the default one as seen above and a precision based one. To use the precision based strategy you need to configure it:

Configurator.DateTimeHumanizeStrategy = new PrecisionDateTimeHumanizeStrategy(precision: .75);
Configurator.DateTimeOffsetHumanizeStrategy = new PrecisionDateTimeOffsetHumanizeStrategy(precision: .75); // configure when humanizing DateTimeOffset

The default precision is set to .75 but you can pass your desired precision too. With precision set to 0.75:

44 seconds => 44 seconds ago/from now
45 seconds => one minute ago/from now
104 seconds => one minute ago/from now
105 seconds => two minutes ago/from now

25 days => a month ago/from now

No dehumanization for dates as Humanize is a lossy transformation and the human friendly date is not reversible

Humanize TimeSpan

You can call Humanize on a TimeSpan to a get human friendly representation for it:

TimeSpan.FromMilliseconds(1).Humanize() => "1 millisecond"
TimeSpan.FromMilliseconds(2).Humanize() => "2 milliseconds"
TimeSpan.FromDays(1).Humanize() => "1 day"
TimeSpan.FromDays(16).Humanize() => "2 weeks"

There is an optional precision parameter for TimeSpan.Humanize which allows you to specify the precision of the returned value. The default value of precision is 1 which means only the largest time unit is returned like you saw in TimeSpan.FromDays(16).Humanize(). Here is a few examples of specifying precision:

TimeSpan.FromDays(1).Humanize(
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap