需要將中文名轉爲英文名,這裏需要考慮到姓氏以及名字多音字選擇,這裏記錄一下我實現的一種思路。
以下代碼均使用JS來進行說明。
處理流程
首先需要判斷名字長度以及名字規範
//中文名格式驗證
verifyName: function(str) {
let re = /[^\u4e00-\u9fa5]/;
const isChinese = str => !re.test(str);
if (!isChinese(str) || str.length < 2) {
return false;
}
return true;
},
當名字長度超過兩個子的時候需要判斷複姓的情況,如名字爲歐陽日天,那麼需要詢問用戶姓氏爲歐陽還是歐,這裏只能通過提前預備所有的複姓列表進行檢測。
這裏提供一份我自己整理的複姓列表,下面的doubleFamilyName
就是複姓列表數組
我聲明一個this.isDoubleFamilyName
用來標記是否爲複姓的標記,默認爲0
,如果是複姓則2
,單姓爲1
,這裏是處理邏輯
if (str.length > 2 && doubleFamilyName.indexOf(str.substr(0, 2)) > -1) {
//這裏可以通過一個彈窗來提示用戶選擇
//然後根據用戶選擇來設置this.isDoubleFamilyName的值
} else {
this.isDoubleFamilyName = 1;
}
接下來需要判斷名字中的多音字,注意這裏的多音字是指拼寫不同,音調不同的忽略。這裏需要藉助第三方的庫來將漢字轉爲拼音,我使用的是在github上找的一個庫,倉庫地址在這裏,使用方法很簡單
import pinyin from 'pinyin';
//獲取這個字符串的全部讀音
//得到一個二維數組
//數據格式如[ [ 'zhang', 'zhong' ], [ 'xin' ] ,['liu','ni']]
this.py = pinyin(str, {
heteronym: true, //打開多音字
style: pinyin.STYLE_NORMAL //注音不加聲調
});
let py = this.py; //這裏存全局變量是爲了後面可以複用
這裏聲明一個this.nameSpell
用來保存最後的每個字的讀音數組
考慮到實際使用中文名轉英文名都是轉爲全大寫,這裏我也使用了toUpperCase()方法來轉換,如不需要自己手動去除這個方法即可
if (py.some(i => i.length > 1)) { //判斷這個二維數組中是否有哪一項含有多音字
//這裏讓用戶選擇具體的讀音並賦值給this.nameSpell
//這裏涉及到一個排列組合的問題,具體代碼可以參考博客底部的代碼參考
} else {
this.nameSpell = py.map(i => i[0].toUpperCase());
}
現在我們已經將最後的整個拼音方案獲取到this.nameSpell
,接下來就是處理姓和名的分割了。這裏使用this.firstName
和this.lastName
分別保存。
if (this.nameSpell.length > 0) {
if (this.isDoubleFamilyName == 2) {
this.lastName = this.nameSpell[0] + this.nameSpell[1];
this.firstName = this.nameSpell.slice(2).join('');
} else if (this.isDoubleFamilyName == 1) {
this.lastName = this.nameSpell[0];
this.firstName = this.nameSpell.slice(1).join('');
}
}
到此我們已經完成整個從中文名轉爲英文名的過程。
代碼參考
二維數組的排列組合
/**
* 傳入一個二維數組,如[ [ 'zhang', 'zhong' ], [ 'xin' ] ,['liu']]
* 返回[['zhang','xin','liu'],['zhong','xin','liu']]
*/
function(py) {
let lengthArr = [];
let productArr = [];
let result = [];
let length = 1;
for (let i = 0; i < py.length; i++) {
let len = py[i].length;
lengthArr.push(len);
let product = i === 0 ? 1 : py[i - 1].length * productArr[i - 1];
productArr.push(product);
length *= len;
}
for (let i = 0; i < length; i++) {
let resultItem = [];
for (let j = 0; j < py.length; j++) {
resultItem.push(
py[j][Math.floor(i / productArr[j]) % lengthArr[j]].toUpperCase()
);
}
result.push(resultItem);
}
return result;
}