当前位置: 首页>>代码示例>>Golang>>正文


Golang language.Parse函数代码示例

本文整理汇总了Golang中golang.org/x/text/language.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ExampleParse_errors

func ExampleParse_errors() {
	for _, s := range []string{"Foo", "Bar", "Foobar"} {
		_, err := language.Parse(s)
		if err != nil {
			if inv, ok := err.(language.ValueError); ok {
				fmt.Println(inv.Subtag())
			} else {
				fmt.Println(s)
			}
		}
	}
	for _, s := range []string{"en", "aa-Uuuu", "AC", "ac-u"} {
		_, err := language.Parse(s)
		switch e := err.(type) {
		case language.ValueError:
			fmt.Printf("%s: culprit %q\n", s, e.Subtag())
		case nil:
			// No error.
		default:
			// A syntax error.
			fmt.Printf("%s: ill-formed\n", s)
		}
	}
	// Output:
	// foo
	// Foobar
	// aa-Uuuu: culprit "Uuuu"
	// AC: culprit "ac"
	// ac-u: ill-formed
}
开发者ID:davidsoloman,项目名称:beats,代码行数:30,代码来源:examples_test.go

示例2: preferredLanguages

func preferredLanguages() []language.Tag {
	var langs []language.Tag
	//	langs = append(langs, language.MustParse("es_MX"))
	nav := js.Global.Get("navigator")
	if cordova.IsMobile() {
		var wg sync.WaitGroup
		wg.Add(1)
		nav.Get("globalization").Call("getPreferredLanguage",
			func(l string) {
				defer wg.Done()
				if tag, err := language.Parse(l); err == nil {
					langs = append(langs, tag)
				}
			}, func() {
				defer wg.Done()
				// ignore any error
			})
		wg.Wait()
	}
	if languages := js.Global.Get("navigator").Get("languages"); languages != nil {
		for i := 0; i < languages.Length(); i++ {
			if tag, err := language.Parse(languages.Index(i).String()); err == nil {
				langs = append(langs, tag)
			}
		}
	}
	if tag, err := language.Parse(js.Global.Get("navigator").Get("language").String()); err == nil {
		langs = append(langs, tag)
	}
	return langs
}
开发者ID:FlashbackSRS,项目名称:flashback,代码行数:31,代码来源:l10n.go

示例3: Translate

// Translate one or more strings of text from a source language to a target
// language. All inputs must be in the same language.
//
// The target parameter supplies the language to translate to. The supported
// languages are listed at
// https://cloud.google.com/translate/v2/translate-reference#supported_languages.
// You can also call the SupportedLanguages method.
//
// The returned Translations appear in the same order as the inputs.
func (c *Client) Translate(ctx context.Context, inputs []string, target language.Tag, opts *Options) ([]Translation, error) {
	call := c.raw.Translations.List(inputs, target.String()).Context(ctx)
	if opts != nil {
		if s := opts.Source; s != language.Und {
			call.Source(s.String())
		}
		if f := opts.Format; f != "" {
			call.Format(string(f))
		}
		if m := opts.Model; m != "" {
			call.Model(m)
		}
	}
	res, err := call.Do()
	if err != nil {
		return nil, err
	}
	var ts []Translation
	for _, t := range res.Translations {
		var source language.Tag
		if t.DetectedSourceLanguage != "" {
			source, err = language.Parse(t.DetectedSourceLanguage)
			if err != nil {
				return nil, err
			}
		}
		ts = append(ts, Translation{
			Text:   t.TranslatedText,
			Source: source,
			Model:  t.Model,
		})
	}
	return ts, nil
}
开发者ID:trythings,项目名称:trythings,代码行数:43,代码来源:translate.go

示例4: getLangs

func getLangs() (tags []language.Tag) {
	for _, t := range strings.Split(*langs, ",") {
		tag, err := language.Parse(t)
		if err != nil {
			fatalf("gotext: could not parse language %q: %v", t, err)
		}
		tags = append(tags, tag)
	}
	return tags
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:10,代码来源:main.go

示例5: Language

// Language returns the users language code.
// Eg. "en", "es", etc
func Language() string {
	l := locale()

	tag, err := language.Parse(l)
	if err != nil {
		return defaultLanguage
	}

	base, _ := tag.Base()

	return base.String()
}
开发者ID:KeizerDev,项目名称:s,代码行数:14,代码来源:providers.go

示例6: Region

// Region returns the users region code.
// Eg. "US", "GB", etc
func Region() string {
	l := locale()

	tag, err := language.Parse(l)
	if err != nil {
		return defaultRegion
	}

	region, _ := tag.Region()

	return region.String()
}
开发者ID:KeizerDev,项目名称:s,代码行数:14,代码来源:providers.go

示例7: Init

// Init 初始化 locale 包并返回当前系统默认的本地化语言信息。
func Init() (language.Tag, error) {
	for id, messages := range locales {
		tag := language.MustParse(id)
		for key, val := range messages {
			message.SetString(tag, key, val)
		}
	}

	localeName, err := getLocaleName()
	if err != nil {
		return language.Und, err
	}

	return language.Parse(localeName)
}
开发者ID:caixw,项目名称:apidoc,代码行数:16,代码来源:locale.go

示例8: TestConsts

// 对一些堂量的基本检测。
func TestConsts(t *testing.T) {
	a := assert.New(t)

	a.True(version.SemVerValid(Version))
	a.True(len(Name) > 0)
	a.True(is.URL(RepoURL))
	a.True(is.URL(OfficialURL))
	a.True(len(ConfigFilename) > 0).True(strings.IndexAny(ConfigFilename, "/\\") < 0)
	a.True(len(DefaultTitle) > 0)
	a.True(len(DefaultGroupName) > 0).True(strings.IndexAny(DefaultGroupName, "/\\") < 0)
	a.True(len(Profile) > 0).True(strings.IndexAny(Profile, "/\\") < 0)

	tag, err := language.Parse(DefaultLocale)
	a.NotError(err).NotEqual(tag, language.Und)
}
开发者ID:caixw,项目名称:apidoc,代码行数:16,代码来源:app_test.go

示例9: parseCollation

// parseCollation parses XML files in the collation directory of the CLDR core.zip file.
func parseCollation(b *build.Builder) {
	d := &cldr.Decoder{}
	d.SetDirFilter("collation")
	data := decodeCLDR(d)
	for _, loc := range data.Locales() {
		x, err := data.LDML(loc)
		failOnError(err)
		if skipLang(x.Identity.Language.Type) {
			continue
		}
		cs := x.Collations.Collation
		sl := cldr.MakeSlice(&cs)
		if len(types.s) == 0 {
			sl.SelectAnyOf("type", x.Collations.Default())
		} else if !types.all {
			sl.SelectAnyOf("type", types.s...)
		}
		sl.SelectOnePerGroup("alt", altInclude())

		for _, c := range cs {
			id, err := language.Parse(loc)
			if err != nil {
				fmt.Fprintf(os.Stderr, "invalid locale: %q", err)
				continue
			}
			// Support both old- and new-style defaults.
			d := c.Type
			if x.Collations.DefaultCollation == nil {
				d = x.Collations.Default()
			} else {
				d = x.Collations.DefaultCollation.Data()
			}
			// We assume tables are being built either for search or collation,
			// but not both. For search the default is always "search".
			if d != c.Type && c.Type != "search" {
				typ := c.Type
				if len(c.Type) > 8 {
					typ = typeMap[c.Type]
				}
				id, err = id.SetTypeForKey("co", typ)
				failOnError(err)
			}
			t := b.Tailoring(id)
			c.Process(processor{t})
		}
	}
}
开发者ID:YaSuenag,项目名称:hsbeat,代码行数:48,代码来源:maketables.go

示例10: TypeCheck

// TypeCheck implements the Expr interface.
func (expr *CollateExpr) TypeCheck(ctx *SemaContext, desired Type) (TypedExpr, error) {
	_, err := language.Parse(expr.Locale)
	if err != nil {
		return nil, errors.Wrapf(err, "invalid locale %s", expr.Locale)
	}
	subExpr, err := expr.Expr.TypeCheck(ctx, TypeString)
	if err != nil {
		return nil, err
	}
	switch t := subExpr.ResolvedType().(type) {
	case tString, TCollatedString:
		expr.Expr = subExpr
		expr.typ = TCollatedString{expr.Locale}
		return expr, nil
	default:
		return nil, fmt.Errorf("incompatible type for COLLATE: %s", t)
	}
}
开发者ID:BramGruneir,项目名称:cockroach,代码行数:19,代码来源:type_check.go

示例11: InitI18n

//Read all .ini files in dir, where the filenames are BCP 47 tags
//Use the language matcher to get the best match for the locale preference
func InitI18n(locale, dir string) {
	pref := language.Make(locale) // falls back to en-US on parse error

	files, err := ioutil.ReadDir(dir)
	if err != nil {
		log.Fatal(err)
	}

	serverLangs := make([]language.Tag, 1)
	serverLangs[0] = language.AmericanEnglish // en-US fallback
	for _, file := range files {
		if filepath.Ext(file.Name()) == ".ini" {
			name := strings.TrimSuffix(file.Name(), ".ini")
			tag, err := language.Parse(name)
			if err == nil {
				serverLangs = append(serverLangs, tag)
			}
		}
	}
	matcher := language.NewMatcher(serverLangs)
	tag, _, _ := matcher.Match(pref)

	fname := filepath.Join(dir, tag.String()+".ini")
	conf, err := configparser.Read(fname)
	if err != nil {
		log.Fatal("cannot read translation file for", tag.String(), err)
	}

	formats, err := conf.Section("formats")
	if err != nil {
		log.Fatal("Cannot read formats sections in translations for", tag.String(), err)
	}
	translations, err := conf.Section("strings")
	if err != nil {
		log.Fatal("Cannot read strings sections in translations for", tag.String(), err)
	}

	i18nProvider = &i18n{
		translation_dir: dir,
		formats:         formats.Options(),
		translations:    translations.Options(),
		locale:          tag,
	}
}
开发者ID:ZiRo-,项目名称:srndv2,代码行数:46,代码来源:i18n.go

示例12: SupportedLanguages

// SupportedLanguages returns a list of supported languages for translation.
// The target parameter is the language to use to return localized, human
// readable names of supported languages.
func (c *Client) SupportedLanguages(ctx context.Context, target language.Tag) ([]Language, error) {
	call := c.raw.Languages.List().Context(ctx).Target(target.String())
	res, err := call.Do()
	if err != nil {
		return nil, err
	}
	var ls []Language
	for _, l := range res.Languages {
		tag, err := language.Parse(l.Language)
		if err != nil {
			return nil, err
		}
		ls = append(ls, Language{
			Name: l.Name,
			Tag:  tag,
		})
	}
	return ls, nil
}
开发者ID:trythings,项目名称:trythings,代码行数:22,代码来源:translate.go

示例13: DetectLanguage

// DetectLanguage attempts to determine the language of the inputs. Each input
// string may be in a different language.
//
// Each slice of Detections in the return value corresponds with one input
// string. A slice of Detections holds multiple hypotheses for the language of
// a single input string.
func (c *Client) DetectLanguage(ctx context.Context, inputs []string) ([][]Detection, error) {
	call := c.raw.Detections.List(inputs).Context(ctx)
	res, err := call.Do()
	if err != nil {
		return nil, err
	}
	var result [][]Detection
	for _, raws := range res.Detections {
		var ds []Detection
		for _, rd := range raws {
			tag, err := language.Parse(rd.Language)
			if err != nil {
				return nil, err
			}
			ds = append(ds, Detection{
				Language:   tag,
				Confidence: rd.Confidence,
				IsReliable: rd.IsReliable,
			})
		}
		result = append(result, ds)
	}
	return result, nil
}
开发者ID:trythings,项目名称:trythings,代码行数:30,代码来源:translate.go

示例14: newColumnTableDef

func newColumnTableDef(
	name Name, typ ColumnType, qualifications []NamedColumnQualification,
) (*ColumnTableDef, error) {
	d := &ColumnTableDef{
		Name: name,
		Type: typ,
	}
	d.Nullable.Nullability = SilentNull
	for _, c := range qualifications {
		switch t := c.Qualification.(type) {
		case ColumnCollation:
			locale := string(t)
			_, err := language.Parse(locale)
			if err != nil {
				return nil, errors.Wrapf(err, "invalid locale %s", locale)
			}
			switch s := d.Type.(type) {
			case *StringColType:
				d.Type = &CollatedStringColType{s.Name, s.N, locale}
			case *CollatedStringColType:
				return nil, errors.Errorf("multiple COLLATE declarations for column %q", name)
			default:
				return nil, errors.Errorf("COLLATE declaration for non-string-typed column %q", name)
			}
		case *ColumnDefault:
			if d.HasDefaultExpr() {
				return nil, errors.Errorf("multiple default values specified for column %q", name)
			}
			d.DefaultExpr.Expr = t.Expr
			d.DefaultExpr.ConstraintName = c.Name
		case NotNullConstraint:
			if d.Nullable.Nullability == Null {
				return nil, errors.Errorf("conflicting NULL/NOT NULL declarations for column %q", name)
			}
			d.Nullable.Nullability = NotNull
			d.Nullable.ConstraintName = c.Name
		case NullConstraint:
			if d.Nullable.Nullability == NotNull {
				return nil, errors.Errorf("conflicting NULL/NOT NULL declarations for column %q", name)
			}
			d.Nullable.Nullability = Null
			d.Nullable.ConstraintName = c.Name
		case PrimaryKeyConstraint:
			d.PrimaryKey = true
			d.UniqueConstraintName = c.Name
		case UniqueConstraint:
			d.Unique = true
			d.UniqueConstraintName = c.Name
		case *ColumnCheckConstraint:
			d.CheckExprs = append(d.CheckExprs, ColumnTableDefCheckExpr{
				Expr:           t.Expr,
				ConstraintName: c.Name,
			})
		case *ColumnFKConstraint:
			if d.HasFKConstraint() {
				return nil, errors.Errorf("multiple foreign key constraints specified for column %q", name)
			}
			d.References.Table = t.Table
			d.References.Col = t.Col
			d.References.ConstraintName = c.Name
		case *ColumnFamilyConstraint:
			if d.HasColumnFamily() {
				return nil, errors.Errorf("multiple column families specified for column %q", name)
			}
			d.Family.Name = t.Family
			d.Family.Create = t.Create
			d.Family.IfNotExists = t.IfNotExists
		default:
			panic(fmt.Sprintf("unexpected column qualification: %T", c))
		}
	}
	return d, nil
}
开发者ID:BramGruneir,项目名称:cockroach,代码行数:73,代码来源:create.go

示例15: GetLocaleTag

// GetLocale creates a new language Tag from a locale
func GetLocaleTag(locale string) (language.Tag, error) {
	return language.Parse(locale)
}
开发者ID:hafeez3000,项目名称:csfw,代码行数:4,代码来源:locale.go


注:本文中的golang.org/x/text/language.Parse函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。