Gender code in php

Функция определения пола по имени

Здравствуйте.
Что-то никак не поддается мне решение данной задачи: «Напишите функцию, которая примет имя человека, а возвратит пол, пытаясь угадать по имени (null – если угадать не удалось)». Уточню, что задача для новичков

Пока написал ветвление, которое будет возвращать NULL, когда имя может быть мужским или женским.

function gender ($name)  $name = mb_strtolower($name); if ($name == 'саша' 

А дальше только предположения , нужно выделить окончание (возможно букву) и на основание, набора окончаний (слов в окончании), сделать проверку.

P.S. я понимаю есть готовые библиотеки, но так как задание для новичков, оно не предполагает использования готовых решений. Так что ошибки в определение приветствуются (сарказм)

Функция — метода класса для определения совпадения имени человека с некоторым заданным
Объявите класс TMan, создающий тип – человека. Элементы – данные класса – имя, возраст человека.

Читайте также:  Php read html headers

Определение пола по фамилии или имени
Есть два столбца с именами и фамилиями. Нужно определить пол -мужской или женский.. Вопрос, как.

Процедура и функция: Функция определения максимальной цифры числа
напишите программу,которая с помощью функции определяющей максимальную цифру числа выводит на экран.

Команда bash для определения имени по IP
Подскажите команду bash определить список сайтов закрепленных за IP

ЦитатаСообщение от ialex25 Посмотреть сообщение

Насколько я знаю, PHP не занимается машинным обучением. Это не то же само, что отличить символы(цифра это или буква).
Создаете 2 массива: женские имена и мужские и производите поиск в них. Можно искать по совпадению части имени, тогда, вероятно, будет множественный ответ. Если имя общее для обоих полов, то выводить соответствующее сообщение.

ialex25, если имя заканчивается на «А» или «Я», то это женское имя, иначе мужское. Ну а если имя на латинице, то NULL.

И ещё, Саша, Шурик, Санчела, это не имена. Мужской пол это Александр, а женский это Александра.

Да я примерно в этом направление и двигался и вроде бы все получилось. Могли бы с точки зрения корректности написания кода взглянуть.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
function gender($name)  $name == 'женя'  elseif ($nameEnds == 'а' || $nameEnds == 'я' /*Наиболее часто встречаемые буквы в конце женских имен*/) { return ucfirst($name) . ' – имя женское.'; } else { return ucfirst($name) . ' – имя мужское.'; } } echo gender('Лиля'); //Лиля – имя женское.

Буду рад любым комментариям, так как недавно начал изучать PHP и любые комментария и критика приветствуется

Источник

EasyCoding45

Write a java program to accept ‘n’ integers from the user and store them in an ArrayList Collection. Display the elements of an ArrayList in Reverse order. In this Tutorial we are going to learn how we can Write a java program to accept ‘n’ integers from the user and store them in an ArrayList Collection.Display the elements of an ArrayList in Reverse order. Program :- import java.util.*; class array < public static void main(String a[]) < Scanner sc=new Scanner(System.in); System.out.println("Enter Limit of ArrayList :"); int n=sc.nextInt(); ArrayList alist=new ArrayList(); System.out.println("Enter Elements of ArrayList :"); for(int i=0;iSystem.out.println(«Original ArrayList is :»+alist); Collections.reverse(alist); System.out.println(«Reverse of a ArrayList is :»+alist); > > Output :-

Image

Define a Student class (roll number, name, percentage). Define a default and parameterized constructor. Keep a count of objects created. Create objects using parameterized constructor and display the object count after each object is created. (Use static member and method). Also display the contents of each object.

In this tutorial ,we are going to learn how we can Define a Student class (roll number, name, percentage). Define a default and parameterized constructor. Keep a count of objects created. Create objects using parameterized constructor and display the object count after each object is created. (Use static member and method). Also display the contents of each object. Program ::— import java.util.*; class student < int rno; String name; float per; student() < System.out.println("You are in default constructor :"); >student(int rno,String name,float per) < this.rno=rno; this.name=name; this.per=per; >static int cnt=0; static void obj() < cnt++; System.out.println("Object created :"+cnt); >void display() < System.out.println("Student roll no:"+rno); System.out.println("Student name:"+name); System.out.println("Student percentage:"+per); >public static void main(String a[])

Image

Create an abstract class Shape with methods calc_area and calc_volume. Derive three classesSphere(radius) , Cone(radius, height) and Cylinder(radius, height), Box(length, breadth, height)from it. Calculate area and volume of all. (Use Method overriding).||EasyCoding45

In this tutorial, We are going to learn how you can Create an abstract class Shape with methods calc_area and calc_volume. and by Deriving three classes Sphere(radius) , Cone(radius, height) and Cylinder(radius, height), Box(length, breadth, height)from it. to Calculate area and volume of all by Using Method overriding. Below Is The Program of Above Question :- abstract class shape < abstract void area(); abstract void volume(); >class sphere extends shape < double pi=3.14; double radius=4.35; void area() < double ar=4*pi*radius*radius; System.out.println("Area of Sphere is :"+ar); >void volume() < double vol=(4/3)*(pi*radius*radius*radius); System.out.println("Volume of Sphere is :"+vol); >> class cone extends shape < double pi=3.14; double radius=4.35; double height=6.45; void area() < double tot=pi*radius*height; System.out.println("Area of cone is :"+tot); >void volume() < doub

Источник

Jmayhak / gender.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

define( ‘GENDER_MALE’ , ‘m’ );
define( ‘GENDER_MALE_FULL’ , ‘male’ );
define( ‘GENDER_FEMALE’ , ‘f’ );
define( ‘GENDER_FEMALE_FULL’ , ‘female’ );
define( ‘GENDER_UNKNOWN’ , ‘u’ );
define( ‘GENDER_UNKNOWN_FULL’ , ‘unknown’ );
function isValidGender ( $ gender )
$ gender = strtolower( $ gender );
$ accepted_values = array (
GENDER_MALE ,
GENDER_MALE_FULL ,
GENDER_FEMALE ,
GENDER_FEMALE_FULL ,
GENDER_UNKNOWN ,
GENDER_UNKNOWN_FULL
);
foreach ( $ accepted_values as $ value )
if ( $ gender == strtolower( $ value ))
return true ;
>
>
return false ;
>
function useGenderShortForm ( $ gender )
if ( $ gender == GENDER_MALE_FULL )
$ gender = GENDER_MALE ;
> else if ( $ gender == GENDER_FEMALE_FULL )
$ gender = GENDER_FEMALE ;
> else if ( $ gender == GENDER_UNKNOWN_FULL )
$ gender = GENDER_UNKNOWN ;
> else
>
return $ gender ;
>
function getGenderLongForm ( $ gender )
if ( $ gender == GENDER_MALE )
$ gender = GENDER_MALE_FULL ;
> else if ( $ gender == GENDER_FEMALE )
$ gender = GENDER_FEMALE_FULL ;
> else if ( $ gender == GENDER_UNKNOWN )
$ gender = GENDER_UNKNOWN_FULL ;
> else
>
return $ gender ;
>

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Get gender from first name in PHP.

License

tuqqu/gender-detector

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

GenderDetector is a PHP package that detects the gender of a person based on first name. It uses the data file from the project ‘gender.c’ by Jörg Michael (details).

composer require tuqqu/gender-detector

Its usage is simple, for any given name it will give you one of the following genders (strings):

male mostly_male unisex mostly_female female 

For an unknown name it will return null . All the gender values are available as constants of the GenderDetector\Gender class for the convenience.

 $genderDetector = new GenderDetector\GenderDetector(); print $genderDetector->detect('Thomas'); // male print $genderDetector->detect('Avery'); // unisex
 print $genderDetector->detect('Želmíra'); // female print $genderDetector->detect('Geirþrúður'); // female

You may specify a country or region.

 print $genderDetector->detect('Robin'); // mostly_male print $genderDetector->detect('Robin', GenderDetector\Country::USA); // mostly_female print $genderDetector->detect('Robin', GenderDetector\Country::FRANCE); // male print $genderDetector->detect('Robin', GenderDetector\Country::IRELAND); // unisex

All the countries are available as constants of the GenderDetector\Country class.

You may want to override the unknown name value. If it is the case, you need to set a new value with setUnknownGender(string $unknown) method.

 $genderDetector = new GenderDetector\GenderDetector(); print $genderDetector->detect('Doe'); // (null) $genderDetector->setUnknownGender(GenderDetector\Gender::UNISEX); print $genderDetector->detect('Doe'); // unisex

If you happen to have an alternative data file, you might pass it to the GenderDetector constructor’s first argument. Additionally you may add new dictionary files with addDictionaryFile(string $path) method.

 $genderDetector = new GenderDetector\GenderDetector('custom_file_path/dict.txt'); $genderDetector->addDictionaryFile('custom_file_path/another_dict.txt');

Note that each GenderDetector instantiation triggers file parsing, so you might want to avoid reading the same file twice.

The GenderDetector is licensed under the MIT License.

The data file data/nam_dict.txt is licensed under the GNU Free Documentation License.

Источник

Оцените статью