简体   繁体   English

单复数的功能切换?

[英]function switching between singular and plural?

I'm looking for a function that given a string it switches the string to singular/plural.我正在寻找一个函数,它给定一个字符串,它将字符串切换为单数/复数。 I need it to work for european languages other than English.我需要它来处理英语以外的欧洲语言。

Are there any functions that can do the trick?是否有任何功能可以做到这一点? (Given a string to convert and the language?) (给定要转换的字符串和语言?)

Thanks谢谢

Here is my handy function:这是我方便的功能:

function plural( $amount, $singular = '', $plural = 's' ) {
    if ( $amount === 1 ) {
        return $singular;
    }
    return $plural;
}

By default, it just adds the 's' after the string.默认情况下,它只是在字符串后添加“s”。 For example:例如:

echo $posts . ' post' . plural( $posts );

This will echo '0 posts', '1 post', '2 posts', '3 posts', etc. But you can also do:这将回显“0 个帖子”、“1 个帖子”、“2 个帖子”、“3 个帖子”等。但您也可以这样做:

echo $replies . ' repl' . plural( $replies, 'y', 'ies' );

Which will echo '0 replies', '1 reply', '2 replies', '3 replies', etc. Or alternatively:这将回显“0 条回复”、“1 条回复”、“2 条回复”、“3 条回复”等。或者:

echo $replies . ' ' . plural( $replies, 'reply', 'replies' );

And it works for some other languages too.它也适用于其他一些语言。 For example, in Spanish I do:例如,在西班牙语中,我这样做:

echo $comentarios . ' comentario' . plural( $comentarios );

Which will echo '0 comentarios', '1 comentario', '2 comentarios', '3 comentarios', etc. Or if adding an 's' is not the way, then:这将回显 '0 comentarios', '1 comentario', '2 comentarios', '3 comentarios' 等。或者如果添加 's' 不是方法,那么:

echo $canciones . ' canci' . plural( $canciones, 'ón', 'ones' );

Which will echo '0 canciones', '1 canción', '2 canciones', '3 canciones', etc.这将回显“0 canciones”、“1 canciones”、“2 canciones”、“3 canciones”等。

This is not easy: each language has its own rules for forming plurals of nouns.这并不容易:每种语言都有自己的名词复数规则。 In English it tends to be that you put "-s" on the end of a word, unless it ends in "-x", "-s", "-z", "-sh", "-ch" in which case you add "-es".在英语中,通常将“-s”放在单词的末尾,除非它以“-x”、“-s”、“-z”、“-sh”、“-ch”结尾,其中如果您添加“-es”。 But then there's "mouse"=>"mice", "sheep"=>"sheep" etc.但是还有“鼠标”=>“老鼠”、“羊”=>“羊”等。

The first thing to do, then, is to find out what the rule(s) are for forming the plural from the singular noun in the language(s) you want to work with.然后,首先要做的是找出在您要使用的语言中从单数名词形成复数的规则是什么。 But that's not the whole solution.但这不是全部的解决方案。 Another problem is recognising nouns.另一个问题是识别名词。 If you are given a noun, and need to convert it from singular to plural that's not too hard, but if you are given a piece of free text and you have to find the singular nouns and convert them to plural, that's a lot harder.如果给您一个名词,并且需要将其从单数转换为复数,这并不太难,但是如果给您一段自由文本,您必须找到单数名词并将其转换为复数,那就要困难得多。 You can get lists of nouns, but of course some words can be nouns and verbs ("hunt", "fish", "break" etc.) so then you need to parse the text to identify the nouns.您可以获得名词列表,但当然有些单词可以是名词和动词(“hunt”、“fish”、“break”等),因此您需要解析文本以识别名词。

It's a big problem.这是一个大问题。 There's probably an AI system out there that would do what you need, but I don't imagine there'll be anything free that does it all.可能有一个 AI 系统可以满足您的需求,但我不认为会有任何免费的东西可以做到这一切。

There is no function built into PHP for this type of operation. PHP 中没有内置用于此类操作的函数。 There are, however, some tools that you may be able to use to help accomplish your goal.但是,您可以使用一些工具来帮助实现目标。

There is an unofficial Google Dictionary API which contains information on plurals.有一个非官方的 Google Dictionary API,其中包含有关复数的信息。 You can read more about that method here .您可以在此处阅读有关该方法的更多信息。 You'll need to parse a JSON object to find the appropriate items and this method tends to be a little bit slow.您需要解析一个 JSON 对象以找到合适的项目,而这种方法往往有点慢。

The other method that comes to mind is to use aspell, or one of its relatives.想到的另一种方法是使用 aspell 或它的一个亲戚。 I'm not sure how accurate the dictionaries are for languages other than English but I've used aspell to expand words into their various forms.我不确定这些词典对于英语以外的语言有多准确,但我已经使用 aspell 将单词扩展为各种形式。

I know this is not the most helpful answer, but hopefully it gives you a general direction to search in.我知道这不是最有帮助的答案,但希望它为您提供了搜索的一般方向。

English Only Solution仅英文解决方案

Here is a PHP class that has worked flawlessly for me thus far: http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/这是迄今为止对我来说完美无缺的 PHP 类: http : //kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/

Here it is as a Gist in case that site goes away: https://gist.github.com/tbrianjones/ba0460cc1d55f357e00b这里是一个要点,以防网站消失: https : //gist.github.com/tbrianjones/ba0460cc1d55f357e00b

This is a small class and could easily and quickly be converted to other languages.这是一个小班级,可以轻松快速地转换为其他语言。

Here is a quick function that I usually use for less complex scenarios:这是我通常用于不太复杂的场景的快速功能:

public static function getPluralPrase($phrase,$value){
    $plural='';
    if($value>1){
        for($i=0;$i<strlen($phrase);$i++){
            if($i==strlen($phrase)-1){
                $plural.=($phrase[$i]=='y')? 'ies':(($phrase[$i]=='s'|| $phrase[$i]=='x' || $phrase[$i]=='z' || $phrase[$i]=='ch' || $phrase[$i]=='sh')? $phrase[$i].'es' :$phrase[$i].'s');
            }else{
                $plural.=$phrase[$i];
            }
        }
        return $plural;
    }
    return $phrase;
}

Although for a more complex solution you can go with @T.尽管对于更复杂的解决方案,您可以使用@T。 Brian Jones' Solution布赖恩琼斯的解决方案

I like the answer of James Constantino.我喜欢詹姆斯康斯坦丁诺的回答。 Simple and efficient, and you're sure to master every case, in any language.简单而高效,您一定会掌握任何语言的每种情况。 Though one must write more code (twice the common part of the word, namely).尽管必须编写更多代码(即这个词的常见部分的两倍)。

I also like, of course, the TBrianJones solution, but it works only with English (as is. I can easily enhance it for my usual European languages, German, French, Spanish, Italian and Portuguese).当然,我也喜欢 TBrianJones 解决方案,但它仅适用于英语(按原样。我可以轻松地针对我常用的欧洲语言、德语、法语、西班牙语、意大利语和葡萄牙语增强它)。 Thanks for it.谢谢你。 If you know the frequency of the words that will be used, you can optimize it by reorganizing the lines.如果您知道将要使用的单词的频率,您可以通过重新组织行来优化它。

Also Felipe's proposal is good, and btw plebiscited. Felipe 的提议也很好,顺便说一句,已经全民公决了。

But in every solution, I found what I consider as a bug: each of you use the singular form only for the value 1, and the plural form for every other case.但是在每个解决方案中,我都发现了一个我认为的错误:你们每个人只对值 1 使用单数形式,对其他情况使用复数形式。 Which is obviously wrong for negative values, but also --at least in French-- for values strictly lower than 2.这对于负值显然是错误的,但对于严格低于 2 的值也是 - 至少在法语中。

So here is my proposal, taking James's code as the base, optimized:所以这是我的建议,以詹姆斯的代码为基础,优化:

function singleOrPlural($amount, $singular, $plural) {
  return (abs($amount)>=2
    ? $amount.' '.$plural 
    : $amount.' '.$singular
  );
}

So a code like所以像这样的代码

echo "We bought ".singleOrPlural(1.5, "pound", "pounds")
    ." of apples and ".singleOrPlural(2, "pound", "pounds")." of bread.";

will give会给

We bought 1.5 pound of apples and 2 pounds of bread.

which is correct.哪个是正确的。

For the zero value, I cannot understand the reason of a plural, since there is none of the object, but maybe anglosaxon natives are used with that.对于零值,我无法理解复数的原因,因为没有对象,但也许盎格鲁萨克森本地人与它一起使用。

HTH, M. HTH,M。

I came up with a rather easy solution for something like this.对于这样的事情,我想出了一个相当简单的解决方案。 However, this depends on some prior knowledge of general PHP as well as a custom mySQLi class, that can be found here (which explains my use of num_rows .但是,这取决于一般 PHP 的一些先验知识以及可以在此处找到的自定义 mySQLi 类(这解释了我对num_rows使用。

In my case, I needed to pull up a number of notes from a database and say "1 note" and then the word "notes" for everything after 1, as well as something to say "0 notes".就我而言,我需要从数据库中提取一些笔记,然后说“1 个笔记”,然后是 1 之后的所有内容的“笔记”一词,以及说“0 个笔记”的内容。

To pull from the database and do a count, I had to use: $total_notes = $database->num_rows("SELECT notes_id FROM $notes_db");要从数据库中提取并进行计数,我必须使用: $total_notes = $database->num_rows("SELECT notes_id FROM $notes_db");

And then the code to echo the value...然后是回显值的代码......

<?php
 if($total_notes === 1){
 echo '<strong>1</strong> note.';
 }elseif($total_notes > 1){
 echo '<strong>'.$total_notes.'</strong> notes.';                                                                           
 }elseif($total_notes === 0){
 echo '<strong>0</strong> notes.';                                                                      
 }
?>

For anyone still stumbling across this in 2021, I suggest using the Inflector package from Doctrine.对于 2021 年仍然遇到此问题的任何人,我建议使用 Doctrine 的Inflector 包

Doctrine Inflector is a small library that can perform string manipulations with regard to uppercase/lowercase and singular/plural forms of words. Doctrine Inflector 是一个小型库,可以对大写/小写和单复数形式的单词执行字符串操作。

At time of writing, it supports English, French, Norwegian (bokmal), Portuguese, Spanish and Turkish.在撰写本文时,它支持英语、法语、挪威语(博克马尔语)、葡萄牙语、西班牙语和土耳其语。

Simply install it using composer: composer require doctrine/inflector and use it like this:只需使用 composer 安装它: composer require doctrine/inflector并像这样使用它:

<?php
// Composer autoloading (your project probably already does this)
require __DIR__ . '/vendor/autoload.php';

// Build the inflector:
$inflector = \Doctrine\Inflector\InflectorFactory::create()->build();

// Singularize a word:
$inflector->singularize('houses'); // house
$inflector->singularize('vertices');  // vertex

I have a multilanguage solution.我有一个多语言解决方案。

 function howmany($number,$singular,$plural) {
      if($number==1) return $number.' '.$singular;
      else return $number.' '.$plural;
 }

Call the function like so:像这样调用函数:

echo howmany($variablenumber,upcase('kaibigan'),upcase('ng kaibigan'));

Hope this helps!希望这可以帮助!

You can try the following,您可以尝试以下方法,

if ( !function_exists('pluralize') ) {
    function pluralize( $amount, $singular, $plural, $show=false ) {
        $OP = $show ? $amount.' ' : '';
        $OP .= ( $amount == 1 ) ? $singular : $plural;
        return $OP;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM