| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688 |
- 'use strict';
- import moment from 'moment';
- import os from 'os';
- import iconv from 'iconv-lite';
- /**
- * 字符串工具类集合
- *
- * 提供各种字符串处理功能,包括:
- * - 字符串补零、修剪空格
- * - 引号转义与替换
- * - 子字符串截取
- * - 全量字符串替换
- * - 数字/中文/英文验证
- * - IP地址处理
- * - 时间格式化
- * - 年级计算
- * - 哈希表实现
- * - 金额格式化
- * - 数组排序
- * - 循环熔断
- * - 英语单词提取
- *
- * 所有方法均为静态工具方法,可直接调用。
- */
- /**
- * 字符串工具类集合,提供多种字符串处理功能
- *
- * @namespace stringUtils
- * @property {Function} AddZero - 给字符串左侧补零
- * @property {Function} Trim - 删除字符串两端的空格
- * @property {Function} LTrim - 删除字符串左侧的空格
- * @property {Function} RTrim - 删除字符串右侧的空格
- * @property {Function} AddSingleQuotes - 转义单引号
- * @property {Function} SubStr - 截取子字符串
- * @property {Function} ReplaceSingleQuotes - 替换单引号为双单引号
- * @property {Function} ReplaceDoubleQuotes - 替换双引号为中文引号
- * @property {Function} ReplaceAllString - 替换字符串中所有匹配项
- * @property {Function} IsNumber - 判断字符串是否为纯数字
- * @property {Function} GetServerIP - 获取服务器IP地址
- * @property {Function} IsArray - 判断对象是否为数组
- * @property {Function} ExportExcelRes - 设置Excel导出的响应头
- * @property {Function} SetEncode - 字符编码转换
- * @property {Function} SetDecode - 字符解码
- * @property {Function} ChangeXML - 将JSON转换为XML格式
- * @property {Function} Random - 生成指定范围内的随机整数
- * @property {Function} RandomArray - 随机打乱数组顺序
- * @property {Function} RemoveJSONNull - 移除JSON数组中的null值
- * @property {Function} GetDateTimeFormat - 人性化时间格式化
- * @property {Function} GetGrade - 根据生日计算年级
- * @property {Function} GetGrade2 - 根据年级数字返回对应年级名称
- * @property {Function} getMinuteSecond - 将秒数转换为分钟/秒格式
- * @property {Function} FormatMoney - 将金额转换为格式化字符串
- * @property {Function} FormatPercentageToFigure - 将百分比转换为数字
- * @property {Function} SortArrayByStringLength - 根据字符串长度排序数组
- * @property {Function} HasChinese - 判断整句是否包含中文
- * @property {Function} SentenceChinesePosition - 返回句中中文的位置
- * @property {Function} IsChinese - 判断是否是中文
- * @property {Function} IsEnglish - 判断是否是英文
- * @property {Function} loopBreaker - 循环熔断函数
- * @property {Function} getGroupName - 获取小组名称
- * @property {Function} CheckIsArray - 检查是否为数组
- * @property {Function} GetOrdinalPostfix - 获取序数后缀
- * @property {Function} TrimEndZero - 去除数字末尾多余的0
- * @property {Function} IsValidIP - 验证IP地址格式
- * @property {Function} IsValidChineseNumberParentheses - 验证字符串是否只包含汉字、数字、字母和括号
- * @property {Function} GetClientIP - 获取客户端真实IP地址
- * @property {Function} cleanWord - 清理单词中的非字母字符
- * @property {Function} extractEnglishWords - 从文本中提取英语单词
- */
- // 不规则动词映射
- const irregularVerbs = {
- 'arise': ['arose', 'arisen', 'arising', 'arises'],
- 'awake': ['awoke', 'awoken', 'awaking', 'awakes'],
- 'backslide': ['backslid', 'backslidden', 'backsliding', 'backslides'],
- 'become': ['became', 'become', 'becoming', 'becomes'], // 已有,但确保完整
- 'behold': ['beheld', 'beholding', 'beholds'],
- 'bend': ['bent', 'bending', 'bends'],
- 'bet': ['bet', 'betting', 'bets'],
- 'bid': ['bid', 'bidding', 'bids'],
- 'bind': ['bound', 'binding', 'binds'],
- 'bleed': ['bled', 'bleeding', 'bleeds'],
- 'blow': ['blew', 'blown', 'blowing', 'blows'],
- 'break': ['broke', 'broken', 'breaking', 'breaks'],
- 'breed': ['bred', 'breeding', 'breeds'],
- 'bring': ['brought', 'bringing', 'brings'],
- 'build': ['built', 'building', 'builds'],
- 'burn': ['burnt', 'burned', 'burning', 'burns'],
- 'burst': ['burst', 'bursting', 'bursts'],
- 'buy': ['bought', 'buying', 'buys'],
- 'cast': ['cast', 'casting', 'casts'],
- 'catch': ['caught', 'catching', 'catches'],
- 'choose': ['chose', 'chosen', 'choosing', 'chooses'],
- 'cling': ['clung', 'clinging', 'clings'],
- 'come': ['came', 'coming', 'comes'],
- 'cost': ['cost', 'costing', 'costs'],
- 'creep': ['crept', 'creeping', 'creeps'],
- 'cut': ['cut', 'cutting', 'cuts'],
- 'deal': ['dealt', 'dealing', 'deals'],
- 'dig': ['dug', 'digging', 'digs'],
- 'dive': ['dove', 'dived', 'diving', 'dives'],
- 'do': ['did', 'done', 'doing', 'does'],
- 'draw': ['drew', 'drawn', 'drawing', 'draws'],
- 'dream': ['dreamt', 'dreamed', 'dreaming', 'dreams'],
- 'drink': ['drank', 'drunk', 'drinking', 'drinks'],
- 'drive': ['drove', 'driven', 'driving', 'drives'],
- 'eat': ['ate', 'eaten', 'eating', 'eats'],
- 'fall': ['fell', 'fallen', 'falling', 'falls'],
- 'feed': ['fed', 'feeding', 'feeds'],
- 'feel': ['felt', 'feeling', 'feels'],
- 'fight': ['fought', 'fighting', 'fights'],
- 'find': ['found', 'finding', 'finds'],
- 'fit': ['fit', 'fitted', 'fitting', 'fits'],
- 'flee': ['fled', 'fleeing', 'flees'],
- 'fling': ['flung', 'flinging', 'flings'],
- 'fly': ['flew', 'flown', 'flying', 'flies'],
- 'forbid': ['forbade', 'forbidden', 'forbidding', 'forbids'],
- 'forget': ['forgot', 'forgotten', 'forgetting', 'forgets'],
- 'forgive': ['forgave', 'forgiven', 'forgiving', 'forgives'],
- 'freeze': ['froze', 'frozen', 'freezing', 'freezes'],
- 'get': ['got', 'gotten', 'getting', 'gets'],
- 'give': ['gave', 'given', 'giving', 'gives'],
- 'go': ['went', 'gone', 'going', 'goes'],
- 'grind': ['ground', 'grinding', 'grinds'],
- 'grow': ['grew', 'grown', 'growing', 'grows'],
- 'hang': ['hung', 'hanging', 'hangs'],
- 'have': ['has', 'had', 'having'],
- 'hear': ['heard', 'hearing', 'hears'],
- 'hide': ['hid', 'hidden', 'hiding', 'hides'],
- 'hit': ['hit', 'hitting', 'hits'],
- 'hold': ['held', 'holding', 'holds'],
- 'hurt': ['hurt', 'hurting', 'hurts'],
- 'keep': ['kept', 'keeping', 'keeps'],
- 'kneel': ['knelt', 'kneeling', 'kneels'],
- 'know': ['knew', 'known', 'knowing', 'knows'],
- 'lay': ['laid', 'laying', 'lays'],
- 'lead': ['led', 'leading', 'leads'],
- 'lean': ['leant', 'leaning', 'leans'],
- 'leap': ['leapt', 'leaping', 'leaps'],
- 'learn': ['learnt', 'learned', 'learning', 'learns'],
- 'leave': ['left', 'leaving', 'leaves'],
- 'lend': ['lent', 'lending', 'lends'],
- 'let': ['let', 'letting', 'lets'],
- 'lie': ['lay', 'lain', 'lying', 'lies'],
- 'light': ['lit', 'lighting', 'lights'],
- 'lose': ['lost', 'losing', 'loses'],
- 'make': ['made', 'making', 'makes'],
- 'mean': ['meant', 'meaning', 'means'],
- 'meet': ['met', 'meeting', 'meets'],
- 'mistake': ['mistook', 'mistaken', 'mistaking', 'mistakes'],
- 'pay': ['paid', 'paying', 'pays'],
- 'put': ['put', 'putting', 'puts'],
- 'quit': ['quit', 'quitting', 'quits'],
- 'read': ['read', 'reading', 'reads'],
- 'ride': ['rode', 'ridden', 'riding', 'rides'],
- 'ring': ['rang', 'rung', 'ringing', 'rings'],
- 'rise': ['rose', 'risen', 'rising', 'rises'],
- 'run': ['ran', 'run', 'running', 'runs'],
- 'say': ['said', 'saying', 'says'],
- 'see': ['saw', 'seen', 'seeing', 'sees'],
- 'seek': ['sought', 'seeking', 'seeks'],
- 'sell': ['sold', 'selling', 'sells'],
- 'send': ['sent', 'sending', 'sends'],
- 'set': ['set', 'setting', 'sets'],
- 'shake': ['shook', 'shaken', 'shaking', 'shakes'],
- 'shed': ['shed', 'shedding', 'sheds'],
- 'shine': ['shone', 'shining', 'shines'],
- 'shoot': ['shot', 'shooting', 'shoots'],
- 'show': ['showed', 'shown', 'showing', 'shows'],
- 'shrink': ['shrank', 'shrunk', 'shrinking', 'shrinks'],
- 'shut': ['shut', 'shutting', 'shuts'],
- 'sing': ['sang', 'sung', 'singing', 'sings'],
- 'sink': ['sank', 'sunk', 'sinking', 'sinks'],
- 'sit': ['sat', 'sitting', 'sits'],
- 'sleep': ['slept', 'sleeping', 'sleeps'],
- 'slide': ['slid', 'sliding', 'slides'],
- 'sling': ['slung', 'slinging', 'slings'],
- 'slink': ['slunk', 'slinking', 'slinks'],
- 'smell': ['smelt', 'smelling', 'smells'],
- 'speak': ['spoke', 'spoken', 'speaking', 'speaks'],
- 'speed': ['sped', 'speeding', 'speeds'],
- 'spell': ['spelt', 'spelling', 'spells'],
- 'spend': ['spent', 'spending', 'spends'],
- 'spill': ['spilt', 'spilling', 'spills'],
- 'spin': ['spun', 'spinning', 'spins'],
- 'spit': ['spat', 'spitting', 'spits'],
- 'split': ['split', 'splitting', 'splits'],
- 'spread': ['spread', 'spreading', 'spreads'],
- 'spring': ['sprang', 'sprung', 'springing', 'springs'],
- 'stand': ['stood', 'standing', 'stands'],
- 'steal': ['stole', 'stolen', 'stealing', 'steals'],
- 'stick': ['stuck', 'sticking', 'sticks'],
- 'sting': ['stung', 'stinging', 'stings'],
- 'stink': ['stank', 'stunk', 'stinking', 'stinks'],
- 'strike': ['struck', 'striking', 'strikes'],
- 'strive': ['strove', 'striven', 'striving', 'strives'],
- 'swear': ['swore', 'sworn', 'swearing', 'swears'],
- 'sweep': ['swept', 'sweeping', 'sweeps'],
- 'swim': ['swam', 'swum', 'swimming', 'swims'],
- 'swing': ['swung', 'swinging', 'swings'],
- 'take': ['took', 'taken', 'taking', 'takes'],
- 'teach': ['taught', 'teaching', 'teaches'],
- 'tear': ['tore', 'torn', 'tearing', 'tears'],
- 'tell': ['told', 'telling', 'tells'],
- 'think': ['thought', 'thinking', 'thinks'],
- 'throw': ['threw', 'thrown', 'throwing', 'throws'],
- 'thrust': ['thrust', 'thrusting', 'thrusts'],
- 'tread': ['trod', 'trodden', 'treading', 'treads'],
- 'undergo': ['underwent', 'undergone', 'undergoing', 'undergoes'],
- 'understand': ['understood', 'understanding', 'understands'],
- 'undertake': ['undertook', 'undertaken', 'undertaking', 'undertakes'],
- 'upset': ['upset', 'upsetting', 'upsets'],
- 'wake': ['woke', 'woken', 'waking', 'wakes'],
- 'wear': ['wore', 'worn', 'wearing', 'wears'],
- 'weave': ['wove', 'woven', 'weaving', 'weaves'],
- 'weep': ['wept', 'weeping', 'weeps'],
- 'win': ['won', 'winning', 'wins'],
- 'wind': ['wound', 'winding', 'winds'],
- 'withdraw': ['withdrew', 'withdrawn', 'withdrawing', 'withdraws'],
- 'wring': ['wrung', 'wringing', 'wrings']
- };
- // 不规则形容词/副词映射表
- const irregularAdjectives = {
- 'good': ['better', 'best'],
- 'bad': ['worse', 'worst'],
- 'many': ['more', 'most'],
- 'much': ['more', 'most'],
- 'little': ['less', 'least'],
- 'far': ['further', 'furthest', 'farther', 'farthest'],
- 'old': ['older', 'oldest', 'elder', 'eldest'],
- 'late': ['later', 'latest', 'latter', 'last'],
- 'well': ['better', 'best'],
- 'ill': ['worse', 'worst'],
- 'easy': ['easier', 'easiest'],
- 'happy': ['happier', 'happiest'],
- 'busy': ['busier', 'busiest'],
- 'pretty': ['prettier', 'prettiest'],
- 'heavy': ['heavier', 'heaviest'],
- 'simple': ['simpler', 'simplest'],
- 'clever': ['cleverer', 'cleverest'],
- 'narrow': ['narrower', 'narrowest'],
- 'quiet': ['quieter', 'quietest'],
- 'large': ['larger', 'largest'],
- 'small': ['smaller', 'smallest'],
- 'big': ['bigger', 'biggest'],
- 'hot': ['hotter', 'hottest'],
- 'tall': ['taller', 'tallest'],
- 'short': ['shorter', 'shortest'],
- 'long': ['longer', 'longest'],
- 'high': ['higher', 'highest'],
- 'low': ['lower', 'lowest'],
- 'deep': ['deeper', 'deepest'],
- 'wide': ['wider', 'widest'],
- 'near': ['nearer', 'nearest'],
- 'clean': ['cleaner', 'cleanest'],
- 'quick': ['quicker', 'quickest'],
- 'slow': ['slower', 'slowest'],
- 'strong': ['stronger', 'strongest'],
- 'weak': ['weaker', 'weakest'],
- 'young': ['younger', 'youngest'],
- 'rich': ['richer', 'richest'],
- 'poor': ['poorer', 'poorest'],
- 'thick': ['thicker', 'thickest'],
- 'thin': ['thinner', 'thinnest'],
- 'fast': ['faster', 'fastest'],
- 'hard': ['harder', 'hardest'],
- 'soft': ['softer', 'softest'],
- 'warm': ['warmer', 'warmest'],
- 'cool': ['cooler', 'coolest'],
- 'cold': ['colder', 'coldest'],
- 'bright': ['brighter', 'brightest'],
- 'dark': ['darker', 'darkest'],
- 'light': ['lighter', 'lightest'],
- 'loud': ['louder', 'loudest'],
- 'sweet': ['sweeter', 'sweetest'],
- 'sour': ['sourer', 'sourest'],
- 'bitter': ['bitterer', 'bitterest'],
- 'nice': ['nicer', 'nicest'],
- 'fine': ['finer', 'finest'],
- 'brave': ['braver', 'bravest'],
- 'calm': ['calmer', 'calmest'],
- 'cute': ['cuter', 'cutest'],
- 'fair': ['fairer', 'fairest'],
- 'fresh': ['fresher', 'freshest'],
- 'full': ['fuller', 'fullest'],
- 'glad': ['gladder', 'gladdest'],
- 'great': ['greater', 'greatest'],
- 'kind': ['kinder', 'kindest'],
- 'new': ['newer', 'newest'],
- 'odd': ['odder', 'oddest'],
- 'rare': ['rarer', 'rarest'],
- 'real': ['realer', 'realest'],
- 'safe': ['safer', 'safest'],
- 'same': ['samer', 'samest'],
- 'sure': ['surer', 'surest'],
- 'true': ['truer', 'truest'],
- 'wise': ['wiser', 'wisest']
- };
- // 特殊不规则名词复数形式
- const irregularNouns = {
- 'child': ['children'],
- 'man': ['men'],
- 'woman': ['women'],
- 'foot': ['feet'],
- 'tooth': ['teeth'],
- 'goose': ['geese'],
- 'mouse': ['mice'],
- 'ox': ['oxen'],
- 'person': ['people'],
- 'louse': ['lice'],
- 'leaf': ['leaves'],
- 'life': ['lives'],
- 'knife': ['knives'],
- 'wife': ['wives'],
- 'half': ['halves'],
- 'wolf': ['wolves'],
- 'shelf': ['shelves'],
- 'self': ['selves'],
- 'calf': ['calves'],
- 'thief': ['thieves'],
- 'deer': ['deer'],
- 'sheep': ['sheep'],
- 'fish': ['fish'],
- 'series': ['series'],
- 'species': ['species'],
- 'aircraft': ['aircraft'],
- 'information': ['information'],
- 'money': ['money'],
- 'rice': ['rice'],
- 'equipment': ['equipment'],
- 'furniture': ['furniture'],
- 'datum': ['data'],
- 'phenomenon': ['phenomena'],
- 'criterion': ['criteria']
- };
- export const stringUtils = {
- // 导出不规则字典
- irregularVerbs,
- irregularAdjectives,
- irregularNouns,
- //给字符串左侧补零
- AddZero: (str, length) => {
- while (str.length < length) {
- str = `0${str}`;
- }
- return str;
- },
- //删除左右两端的空格
- Trim: (str) => str.replace(/(^\s*)|(\s*$)/g, ""),
- //删除左边的空格
- LTrim: (str) => str.replace(/(^\s*)/g, ""),
- //删除右边的空格
- RTrim: (str) => str.replace(/(\s*$)/g, ""),
- //转义单引号
- AddSingleQuotes: (str) => str.replace(/'/g, "''"),
- //截取子字符串
- SubStr: (str, start, length) => (!str || str === "") ? str : str.substr(start, length),
- //替换单引号
- ReplaceSingleQuotes: (str) => str.replace(/'/g, "''"),
- //替换双引号
- ReplaceDoubleQuotes: (str) => {
- if (str && str.length > 0) {
- do {
- str = str.replace("\"", "“");
- str = str.replace("\"", "”");
- } while (str.indexOf("\"") >= 0);
- }
- return str;
- },
- //替换字符串中所有匹配项
- ReplaceAllString: (str, replaceStrFrom, replaceStrTo) => {
- if (str && str.length > 0) {
- const reg = new RegExp(replaceStrFrom, "g");
- return str.toString().replace(reg, replaceStrTo);
- }
- return str;
- },
- //判断是否是数字,true:是,false:不是
- IsNumber: (value) => /^\d+$/.test(value),
-
- //获取服务器IP地址
- GetServerIP: () => {
- const interfaces = os.networkInterfaces();
- for (const devName in interfaces) {
- const iface = interfaces[devName];
- for (let i = 0; i < iface.length; i++) {
- const alias = iface[i];
- if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
- return alias.address;
- }
- }
- }
- },
- //判断是否是数组
- IsArray: (obj) => Object.prototype.toString.call(obj) === '[object Array]',
- //导出Excel的Res
- ExportExcelRes: (res, fileName) => {
- res.set({
- //'Content-Type': 'application/vnd.ms-execl;charset=utf-8',
- 'Content-Type': 'application/vnd.ms-execl',
- 'Content-Disposition': "attachment;filename=" + encodeURIComponent(fileName),
- 'Pragma': 'no-cache',
- 'Expires': 0
- });
- return res;
- },
- //转码
- SetEncode: (content, encode) => {
- const buffer = Buffer.from(content);
- return iconv.encode(buffer, encode);
- },
- //解码
- SetDecode: (content, encode) => {
- const buffer = Buffer.from(content);
- return iconv.decode(buffer, encode);
- },
- //将JSON转换为XML格式
- ChangeXML: (json) => {
- const result = [];
- result.push("<xml>\r\n");
- for (const item in json) {
- result.push(`<${item}>`);
- result.push(json[item]);
- result.push(`</${item}>\r\n`);
- }
- result.push("</xml>");
- return result.join("");
- },
- //生成指定范围内的随机整数
- Random: (start, end) => {
- const result = parseInt(Math.random() * (end - start + 1) + start);
- return result;
- },
- //随机打乱数组顺序(使用Fisher-Yates算法变体)
- RandomArray: (arr) => {
- const arrResult = [];
- let maxCount = 0;
- do {
- const rnd = stringUtils.Random(0, arr.length - 1);
- if (arr[rnd]) {
- arrResult.push(arr[rnd]);
- arr[rnd] = null;
- }
- maxCount++;
- } while (arrResult.length < arr.length && maxCount < 10000);
- return arrResult;
- },
- //移除JSON数组中的null值
- RemoveJSONNull: (list) => {
- for (let i = 0; i < list.length; i++) {
- const item = list[i];
- for (const key in item) {
- if (item[key] == null) {
- delete item[key];
- }
- }
- }
- return list;
- },
- //得到格式化的时间为更人性化的刚刚,几分钟前,几小时前等
- //人性化时间格式化(使用moment.js)
- GetDateTimeFormat: (date) => {
- let result = "";
- const time1 = moment(date);
- const today = moment(`${moment().format('YYYY-MM-DD')} 00:00:00`);
- const yesterday = moment(`${moment().add(-1, 'd').format('YYYY-MM-DD')} 00:00:00`);
- const yesterday2 = moment(`${moment().add(-2, 'd').format('YYYY-MM-DD')} 00:00:00`);
- const tomorrow = moment(`${moment().add(1, 'd').format('YYYY-MM-DD')} 00:00:00`);
- const tomorrow2 = moment(`${moment().add(2, 'd').format('YYYY-MM-DD')} 00:00:00`);
- if (time1 < tomorrow) {
- if (moment().diff(time1, "s") < 300) {
- result = "刚刚";
- }
- if (time1 >= today) {
- result = "今天";
- } else if (time1 > yesterday) {
- result = "昨天";
- } else if (time1 > yesterday2) {
- result = "前天";
- } else {
- const daysDiff = moment().diff(time1, "d");
- const monthsDiff = moment().diff(time1, "M");
- result = monthsDiff < 1 ? `${daysDiff}天前` : `${monthsDiff}月前`;
- }
- } else {
- if (time1 < tomorrow2) {
- result = "明天";
- } else {
- const daysDiff = -moment().diff(time1, "d");
- const monthsDiff = -moment().diff(time1, "M");
- result = monthsDiff < 1
- ? `${daysDiff < 2 ? 2 : daysDiff}天后`
- : `${monthsDiff}月后`;
- }
- }
- return result;
- },
- //得到年级
- //根据生日计算年级
- GetGrade: (birthday, returnType) => {
- if (birthday.includes(".")) {
- birthday = birthday.replace(".", "-");
- }
- let result = "";
- if (birthday) {
- const b = moment(birthday);
- const now = moment();
- const diff = now.diff(b, 'months');
- if (returnType === "number") {
- if (diff <= 85) result = 1;
- else if (diff <= 97) result = 2;
- else if (diff <= 109) result = 3;
- else result = 4;
- } else {
- if (diff <= 37) {
- result = `${diff}个月`;
- } else if (diff <= 49) {
- result = "幼儿园小班";
- } else if (diff <= 61) {
- result = "幼儿园中班";
- } else if (diff <= 73) {
- result = "幼儿园大班";
- } else if (diff <= 85) {
- result = "一年级";
- } else if (diff <= 97) {
- result = "二年级";
- } else if (diff <= 109) {
- result = "三年级";
- } else if (diff <= 121) {
- result = "四年级";
- } else if (diff <= 133) {
- result = "五年级";
- } else if (diff <= 145) {
- result = "六年级";
- } else if (diff > 145) {
- result = "初中及以上年龄";
- }
- }
- }
- return result;
- },
- //得到年级
- //根据年级数字返回对应年级名称
- GetGrade2: (gradeNum) => {
- let result = "一年级";
- switch (gradeNum) {
- case 0:
- case 1:
- result = "一年级";
- break;
- case 2:
- result = "二年级";
- break;
- case 3:
- result = "三年级";
- break;
- case 4:
- result = "四年级";
- break;
- case 5:
- result = "五年级";
- break;
- case 6:
- result = "六年级";
- break;
- case 7:
- result = "初一";
- break;
- case 8:
- result = "初二";
- break;
- case 9:
- result = "初三";
- break;
- case 10:
- result = "高一";
- break;
- case 11:
- result = "高二";
- break;
- case 12:
- result = "高三";
- break;
- default:
- result = "大学及成人";
- break;
- }
- return result;
- },
- //将秒数转换为分钟/秒格式
- getMinuteSecond: (second, chs, hasSecond) => {
- if (!second) second = 0;
-
- const secondUnit = chs ? "秒" : "″";
- const minuteUnit = chs ? "分" : "′";
- const hourUnit = chs ? "时" : ":";
-
- if (second < 60) {
- return `${second}${secondUnit}`;
- }
-
- let minute = Math.floor(second / 60);
- second = Math.round((second - minute * 60) * 1000) / 1000;
- if (minute >= 60) {
- const hour = Math.floor(minute / 60);
- minute = minute - hour * 60;
- if (minute === 0 && second === 0) {
- return `${hour}${hourUnit}`;
- } else if (second === 0) {
- return `${hour}${hourUnit}${minute}${minuteUnit}`;
- } else {
- return hasSecond
- ? `${hour}${hourUnit}${minute + 1}${minuteUnit}`
- : `${hour}${hourUnit}${minute}${minuteUnit}${second}${secondUnit}`;
- }
- } else {
- if (second === 0) {
- return `${minute}${minuteUnit}`;
- } else {
- return hasSecond
- ? `${minute + 1}${minuteUnit}`
- : `${minute}${minuteUnit}${second}${secondUnit}`;
- }
- }
- },
- //哈希表的类
- HashTable: class HashTable {
- constructor() {
- this.size = 0;
- this.entry = {};
- }
- add(key, value) {
- if (!this.containsKey(key)) {
- this.size++;
- }
- this.entry[key] = value;
- }
- update(key, value) {
- if (this.containsKey(key)) {
- this.entry[key] = value;
- }
- }
- getValue(key) {
- return this.containsKey(key) ? this.entry[key] : null;
- }
- remove(key) {
- if (this.containsKey(key) && (delete this.entry[key])) {
- this.size--;
- }
- }
- containsKey(key) {
- return (key in this.entry);
- }
- containsValue(value) {
- for (const prop in this.entry) {
- if (this.entry[prop] == value) {
- return true;
- }
- }
- return false;
- }
- getValues() {
- const values = [];
- for (const prop in this.entry) {
- values.push(this.entry[prop]);
- }
- return values;
- }
- getKeys() {
- const keys = [];
- for (const prop in this.entry) {
- keys.push(prop);
- }
- return keys;
- }
- getKeysAndValues() {
- const keysValues = [];
- for (const prop in this.entry) {
- keysValues.push(prop + "###" + this.entry[prop]);
- }
- return keysValues;
- }
- getSize() {
- return this.size;
- }
- clear() {
- this.size = 0;
- this.entry = {};
- }
- },
- //将金额转换为格式化字符串(保留两位小数)
- FormatMoney: (money) => {
- if (money === 0) return "0.00";
-
- let result = (Math.round(money) / 100).toString();
- if (result.includes(".")) {
- if (result.substr(result.indexOf(".")).length < 3) {
- result += "0";
- }
- } else {
- result += ".00";
- }
-
- return result;
- },
- FormatPercentageToFigure: (percentage) => {
- let result;
- if (percentage.indexOf("%") > 0) {
- result = percentage.replace("%", "");
- }
- result = Number(result) / 100;
- return result;
- },
- //排序数组根据字符串长度
- SortArrayByStringLength: (arr) => {
- const result = [];
- const temp = [];
- for (let i = 0; i < 30; i++) {
- temp.push([]);
- }
- for (let i = 0; i < arr.length; i++) {
- const item = arr[i];
- temp[item.length].push(item);
- }
- for (let i = 0; i < temp.length; i++) {
- temp[i].sort();
- for (let j = 0; j < temp[i].length; j++) {
- result.push(temp[i][j]);
- }
- }
- return result;
- },
-
- //返回句中中文的位置
- SentenceChinesePosition: (temp) => {
- let result = -1;
- const reg = /^[\u4e00-\u9fa5]|[\uFE30-\uFFA0]+$/; /*定义验证表达式*/
- if (temp) {
- temp = temp.toString();
- for (let i = 0; i < temp.length; i++) {
- if (reg.test(temp[i])) {
- result = i;
- break;
- }
- }
- }
- return result;
- },
- //判断整句是否有中文
- HasChinese: (temp) => {
- let result = false;
- const reg = /^[\u4e00-\u9fa5]|[\uFE30-\uFFA0]+$/; /*定义验证表达式*/
- if (temp) {
- temp = temp.toString();
- for (let i = 0; i < temp.length; i++) {
- if (reg.test(temp[i])) {
- result = true;
- break;
- }
- }
- }
- return result;
- },
- //判断是否是中文
- IsChinese: (temp) => {
- const reg = /^[\u4e00-\u9fa5\uFE30-\uFFA0]+$/; /*定义验证表达式*/
- return reg.test(temp); /*进行验证*/
- },
- //判断是否是英文
- IsEnglish: (temp) => {
- const reg = new RegExp("^[A-Za-z]+(?:['-][A-Za-z]+)*(?:\\s+[A-Za-z]+(?:['-][A-Za-z]+)*)*$");
- return reg.test(temp); /*进行验证*/
- },
- GetProgramSource: (str) => {
- switch (str) {
- case 98:
- return "拼音";
- case 99:
- return "拼读";
- case 106:
- return "识字";
- case 105:
- return "计算";
- case 164:
- return "口算";
- case 166:
- return "秒过";
- case 186:
- return "语境";
- case 173:
- return "分数线";
- case 90:
- return "专注力";
- case 0:
- return "";
- default:
- return str;
- }
- },
- //循环熔断函数
- loopBreaker: (startTime, second) => {
- if (!second) {
- second = 60;
- }
- if (!startTime) {
- startTime = Date.now();
- }
- if (Date.now() - startTime > second * 1000) {
- throw new Error("Loop Broken!");
- }
- },
- //得到小组名称
- getGroupName: (groupID, isAllName) => {
- let name = "";
- switch (groupID) {
- case 1:
- name = '彩';
- if (isAllName) {
- name = "彩虹";
- }
- break;
- case 2:
- name = '润';
- if (isAllName) {
- name = "润雨";
- }
- break;
- case 3:
- name = '扬';
- if (isAllName) {
- name = "扬帆";
- }
- break;
- }
- return name;
- },
- CheckIsArray: (obj) => {
- return Object.prototype.toString.call(obj) === '[object Array]';
- },
- //得到序数的后缀
- GetOrdinalPostfix: (number) => {
- switch (number) {
- case 1:
- return "st";
- case 2:
- return "nd";
- case 3:
- return "rd";
- default:
- return "th";
- }
- },
- //去除数字末尾多余的0
- TrimEndZero: (input)=> {
- // 判断是否是数字或数字字符串
- if (typeof input === 'number' || (typeof input === 'string' && /^-?\d+(\.\d+)?$/.test(input))) {
- // 转换为数字后转为字符串输出,自动去除末尾多余的0
- return Number(input).toString();
- }
- // 非数字或非数字字符串保持原样返回
- return input;
- },
- // 验证IP地址格式是否有效
- IsValidIP: (ip) => {
- if (!ip) return false;
- // IPv4格式验证
- const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
- if (ipv4Regex.test(ip)) {
- const parts = ip.split('.');
- return parts.every(part => {
- const num = parseInt(part, 10);
- return num >= 0 && num <= 255;
- });
- }
- // IPv6格式验证(简化版)
- const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
- return ipv6Regex.test(ip);
- },
- // 判断字符串是否只包含汉字、数字、大小写字母和全/半角小括号
- IsValidChineseNumberParentheses: (str) => {
- if (!str) return true; // 空字符串视为有效
- // 匹配规则:
- // [\u4e00-\u9fa5]: 匹配汉字
- // 0-9: 匹配数字
- // a-zA-Z: 匹配大小写字母
- // (): 匹配半角小括号
- // (): 匹配全角小括号
- const regex = /^[\u4e00-\u9fa5\da-zA-Z()()]+$/;
- return regex.test(str);
- },
- // 获取客户端真实IP地址的通用函数
- GetClientIP: (ctx) => {
- const request = ctx?.request || ctx;
- const headers = request?.headers || {};
- const socket = request?.socket || ctx?.socket || ctx?.req?.socket;
- // 检查所有可能的代理头
- const proxyHeaders = [
- 'x-forwarded-for',
- 'x-real-ip',
- 'x-client-ip',
- 'x-forwarded',
- 'forwarded-for',
- 'x-cluster-client-ip',
- 'proxy-client-ip',
- 'cf-connecting-ip', // Cloudflare
- 'true-client-ip', // Akamai and Cloudflare
- 'fastly-client-ip', // Fastly
- 'x-original-forwarded-for'
- ];
- let clientIP = null;
- // 1. 首先检查所有代理头
- for (const header of proxyHeaders) {
- const value = headers[header];
- if (value) {
- // 处理可能的多个IP地址(取第一个,通常是最原始的客户端IP)
- clientIP = value.split(',')[0].trim();
- if (stringUtils.IsValidIP(clientIP)) {
- break;
- }
- }
- }
- // 2. 如果没有找到有效的代理头IP,尝试Koa的标准方法
- if (!clientIP || !stringUtils.IsValidIP(clientIP)) {
- clientIP = ctx?.ip || request?.ip;
- }
- // 3. 如果还是没有,尝试socket
- if (!clientIP || !stringUtils.IsValidIP(clientIP)) {
- clientIP = socket?.remoteAddress;
- }
- // 处理IPv6格式
- if (clientIP) {
- // 处理IPv4映射的IPv6地址 (::ffff:127.0.0.1 格式)
- if (clientIP.startsWith('::ffff:')) {
- clientIP = clientIP.substring(7);
- }
- // 处理IPv6本地回环地址
- else if (clientIP === '::1') {
- clientIP = '127.0.0.1';
- }
- }
- return clientIP || '0.0.0.0';
- },
- cleanWord(word) {
- if (!word) return '';
-
- // 去除单词前后的非字母字符
- const cleaned = word.replace(/^[^A-Za-z]+|[^A-Za-z]+$/g, '');
-
- // 保留单词中间的撇号和连字符
- return cleaned.replace(/[^A-Za-z''-]/g, '');
- },
- // 提取英语单词的函数 - 增强版
- extractEnglishWords(texts) {
- //console.group('英语单词提取');
- const words = new Set();
- texts.forEach(item => {
- const text = item;
- //console.log('处理文本:', text);
-
- // 使用多种分隔符分割文本(空格、逗号、句号、感叹号、中文字符等)
- // 这个正则表达式会匹配任何非英文字母、撇号或连字符的字符作为分隔符
- const parts = text.split(/[^A-Za-z''-]+/).filter(Boolean);
-
- //console.log('分割后的部分:', parts);
-
- // 处理每个可能的单词
- parts.forEach(part => {
- // 清理并验证单词
- const cleanWord = this.cleanWord(part);
-
- // 特殊处理单词"I"
- if (cleanWord === 'I' || cleanWord === 'a') {
- words.add(cleanWord); // 添加小写的"i"
- //console.log('添加单词: I (特殊处理)');
- }
- // 处理其他单词(长度>=2)
- else if (cleanWord && cleanWord.length >= 2 && /^[A-Za-z''-]+$/.test(cleanWord)) {
- let lowerWord = cleanWord.toLowerCase();
- if (lowerWord=="i'm"){
- lowerWord="I'm";
- }
- words.add(lowerWord);
- //console.log('添加单词:', lowerWord);
- }
- });
- });
-
- //const result = Array.from(words).sort();
- let result = Array.from(words);
- //console.log('提取结果:', result);
- //console.groupEnd();
- return result;
- },
-
-
- /**
- * 获取单词的所有变形形式
- * @param {string} word - 要获取变形的单词
- * @returns {string[]} - 单词的所有变形形式数组
- */
- getWordAllForms: (word) => {
- if (!word || typeof word !== 'string') {
- return [];
- }
- word = word.trim();
- if (word === '') {
- return [];
- }
-
- // 保留原始单词,包括大小写和标点符号
- const originalWord = word;
-
- // 转换为小写进行处理
- const lowerWord = word.toLowerCase();
-
- // 使用Set存储所有可能的变形,避免重复
- const allForms = new Set([lowerWord]); // 初始包含原单词
-
- // 如果原始单词与小写形式不同,也添加原始单词
- if (originalWord !== lowerWord) {
- allForms.add(originalWord);
- }
-
- // 检查是否是不规则形容词/副词
- for (const [base, forms] of Object.entries(stringUtils.irregularAdjectives)) {
- if (base === lowerWord || forms.includes(lowerWord)) {
- // 添加原形和所有变形
- allForms.add(base);
- forms.forEach(form => allForms.add(form));
- // 不规则形容词处理完成后直接返回,避免进一步处理
- return [...allForms];
- }
- }
- // 检查是否是不规则动词
- for (const [base, forms] of Object.entries(stringUtils.irregularVerbs)) {
- if (base === lowerWord || forms.includes(lowerWord)) {
- // 添加原形和所有变形
- allForms.add(base);
- forms.forEach(form => allForms.add(form));
- // 不规则动词处理完成后直接返回,避免进一步处理
- return [...allForms];
- }
- }
- // 不规则名词检查(单数形式)
- if (stringUtils.irregularNouns[lowerWord]) {
- allForms.add(lowerWord); // 添加原词
- stringUtils.irregularNouns[lowerWord].forEach(form => allForms.add(form));
- // 不规则名词处理完成后直接返回,避免进一步处理
- return [...allForms];
- }
- // 不规则名词检查(复数形式)
- for (const [singular, plurals] of Object.entries(stringUtils.irregularNouns)) {
- if (plurals.includes(lowerWord)) {
- allForms.add(singular);
- allForms.add(lowerWord); // 添加原词
- plurals.forEach(form => allForms.add(form));
- // 不规则名词处理完成后直接返回,避免进一步处理
- return [...allForms];
- }
- }
-
- // 特殊处理一些常见的副词和特殊单词,避免错误的词干提取和变形
- const specialWords = {
- // 情态动词
- 'can': ['can', 'could', 'cannot', "can't"],
- 'may': ['may', 'might'],
- 'shall': ['shall', 'should', "shouldn't"],
- 'will': ['will', 'would', "won't", "wouldn't"],
- 'must': ['must', 'have to', 'has to', 'had to', "mustn't"],
-
- // 特殊形容词及其变形
- 'good': ['good', 'better', 'best', 'well'],
- 'bad': ['bad', 'worse', 'worst', 'badly'],
- 'better': ['better', 'good', 'best', 'well'],
- 'best': ['best', 'good', 'better', 'well'],
- 'worse': ['worse', 'bad', 'worst', 'badly'],
- 'worst': ['worst', 'bad', 'worse', 'badly'],
-
- // 特殊副词
- 'early': ['early', 'earlier', 'earliest'],
- 'only': ['only'],
- 'likely': ['likely', 'more likely', 'most likely'],
- 'friendly': ['friendly', 'friendlier', 'friendliest'],
- 'lovely': ['lovely', 'lovelier', 'loveliest'],
- 'timely': ['timely', 'timelier', 'timeliest'],
- 'weekly': ['weekly'],
- 'monthly': ['monthly'],
- 'yearly': ['yearly'],
- 'daily': ['daily'],
- 'well': ['well', 'better', 'best', 'good'],
- 'badly': ['badly', 'worse', 'worst', 'bad'], // 对应bad的副词形式
-
- // 特殊动词
- 'play': ['play', 'plays', 'played', 'playing'],
- 'stay': ['stay', 'stays', 'stayed', 'staying'],
- 'pay': ['pay', 'pays', 'paid', 'paying'],
- 'lay': ['lay', 'lays', 'laid', 'laying'],
- 'say': ['say', 'says', 'said', 'saying'],
- 'go': ['go', 'goes', 'went', 'gone', 'going'],
- 'went': ['went', 'go', 'gone', 'going', 'goes'],
-
- // 特殊名词
- 'box': ['box', 'boxes'],
- 'fox': ['fox', 'foxes'],
- 'tax': ['tax', 'taxes'],
- 'child': ['child', 'children'],
- 'children': ['children', 'child'],
- 'bush': ['bush', 'bushes'],
- 'dish': ['dish', 'dishes'],
- 'church': ['church', 'churches'],
- 'tomato': ['tomato', 'tomatoes'],
- 'potato': ['potato', 'potatoes'],
- 'hero': ['hero', 'heroes'],
- 'echo': ['echo', 'echoes'],
- // 缩写词
- 'its': ['its'], // 物主代词
- 'it\'s': ['it\'s', 'it is', 'it has'], // it is 的缩写
- 'I\'m': ['I\'m', 'I am'], // I am 的缩写
- 'don\'t': ['don\'t', 'do not'], // do not 的缩写
- 'doesn\'t': ['doesn\'t', 'does not'], // does not 的缩写
- 'can\'t': ['can\'t', 'cannot'], // can not 的缩写
- 'won\'t': ['won\'t', 'will not'], // will not 的缩写
- 'we\'re': ['we are'],
- 'they\'re': ['they are'],
- 'you\'re': ['you are'],
- 'he\'s': ['he is', 'he has'],
- 'she\'s': ['she is', 'she has'],
- 'it\'d': ['it would', 'it had'],
- 'we\'d': ['we would', 'we had'],
- 'they\'d': ['they would', 'they had'],
- 'couldn\'t': ['could not'],
- 'shouldn\'t': ['should not'],
- 'wouldn\'t': ['would not'],
- 'mustn\'t': ['must not'],
- 'haven\'t': ['haven\'t', 'have not'],
- 'hasn\'t': ['hasn\'t', 'has not'],
- 'hadn\'t': ['hadn\'t', 'had not'],
- 'isn\'t': ['isn\'t', 'is not'],
- 'aren\'t': ['aren\'t', 'are not'],
- 'wasn\'t': ['wasn\'t', 'was not'],
- 'weren\'t': ['weren\'t', 'were not'],
- 'should\'ve': ['should have'],
- 'would\'ve': ['would have'],
- 'could\'ve': ['could have']
- };
-
- // 如果是特殊单词,添加预定义的变形
- if (specialWords[lowerWord]) {
- specialWords[lowerWord].forEach(form => allForms.add(form));
- // 处理完特殊词后返回,避免进一步处理
- return [...allForms];
- }
-
- // 检查是否是特殊单词的变形
- for (const [base, forms] of Object.entries(specialWords)) {
- if (forms.includes(lowerWord)) {
- // 添加基本形式
- allForms.add(base);
- // 添加所有变形
- forms.forEach(form => allForms.add(form));
- // 找到特殊单词变形后直接返回,避免进一步处理
- return [...allForms];
- }
- }
-
- // 获取单词的原形(基本形式)
- const possibleBaseWords = [];
-
- // 特殊单词列表,这些单词不应被识别为任何变形
- const specialBaseWords = ['this', 'is', 'was', 'has', 'his', 'its', 'us', 'yes', 'thus', 'plus'];
- if (specialBaseWords.includes(lowerWord)) {
- // 对于特殊基础词,只返回原词
- return [lowerWord];
- }
-
- // 处理规则变形
- // 处理过去式/过去分词 (-ed)
- if (lowerWord.endsWith('ed') && lowerWord.length > 2) {
- // 基本形式
- possibleBaseWords.push(lowerWord.slice(0, -2)); // 常规情况 (walked -> walk)
-
- // 处理双辅音+ed的情况 (stepped -> step, planned -> plan)
- const doubleConsonantPattern = /([bcdfghjklmnpqrstvwxyz])\1ed$/;
- if (doubleConsonantPattern.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -3)); // 如 planned -> plan
- }
-
- // 处理以辅音+y结尾变为ied的情况 (studied -> study)
- if (lowerWord.endsWith('ied') && lowerWord.length > 3) {
- const beforeY = lowerWord.slice(0, -3);
- if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
- possibleBaseWords.push(beforeY + 'y');
- }
- }
-
- // 处理以e结尾的动词变为ed的情况 (liked -> like)
- if (lowerWord.endsWith('ed') && /[bcdfghjklmnpqrstvwxyz]ed$/.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -1)); // 如 liked -> like
- }
- }
-
- // 处理以e结尾的动词加d的情况 (used -> use)
- if (lowerWord.endsWith('d') && !lowerWord.endsWith('ed') && lowerWord.length > 1) {
- possibleBaseWords.push(lowerWord.slice(0, -1)); // 如 used -> use
- }
-
- // 处理现在分词 (-ing)
- if (lowerWord.endsWith('ing') && lowerWord.length > 3) {
- possibleBaseWords.push(lowerWord.slice(0, -3)); // 常规情况 (walking -> walk)
-
- // 处理双辅音+ing的情况 (running -> run)
- const doubleConsonantPattern = /([bcdfghjklmnpqrstvwxyz])\1ing$/;
- if (doubleConsonantPattern.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -4)); // 如 running -> run
- }
-
- // 处理特殊的ing形式 (lying -> lie)
- if (lowerWord.endsWith('ying') && lowerWord.length > 4) {
- possibleBaseWords.push(lowerWord.slice(0, -4) + 'ie'); // 如 lying -> lie
- }
-
- // 处理以辅音+e结尾的动词变为ing的情况 (like -> liking)
- if (lowerWord.endsWith('ing') && /[bcdfghjklmnpqrstvwxyz]ing$/.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -3) + 'e');
- }
- }
-
- // 处理比较级 (-er)
- if (lowerWord.endsWith('er') && lowerWord.length > 2) {
- possibleBaseWords.push(lowerWord.slice(0, -2)); // 常规情况 (faster -> fast)
-
- // 处理双辅音+er的情况 (bigger -> big)
- const doubleConsonantPattern = /([bcdfghjklmnpqrstvwxyz])\1er$/;
- if (doubleConsonantPattern.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -3)); // 如 bigger -> big
- }
-
- // 处理以辅音+y结尾变为ier的情况 (happier -> happy)
- if (lowerWord.endsWith('ier') && lowerWord.length > 3) {
- const beforeY = lowerWord.slice(0, -3);
- if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
- possibleBaseWords.push(beforeY + 'y');
- }
- }
-
- // 处理以e结尾+r的情况 (nicer -> nice)
- if (lowerWord.endsWith('er') && /[^aeiou]er$/.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -2) + 'e'); // 如 nicer -> nice
- }
- }
-
- // 处理最高级 (-est)
- if (lowerWord.endsWith('est') && lowerWord.length > 3) {
- possibleBaseWords.push(lowerWord.slice(0, -3)); // 常规情况 (fastest -> fast)
-
- // 处理双辅音+est的情况 (biggest -> big)
- const doubleConsonantPattern = /([bcdfghjklmnpqrstvwxyz])\1est$/;
- if (doubleConsonantPattern.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -4)); // 如 biggest -> big
- }
-
- // 处理以辅音+y结尾变为iest的情况 (happiest -> happy)
- if (lowerWord.endsWith('iest') && lowerWord.length > 4) {
- const beforeY = lowerWord.slice(0, -4);
- if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
- possibleBaseWords.push(beforeY + 'y');
- }
- }
-
- // 处理以e结尾+st的情况 (nicest -> nice)
- if (lowerWord.endsWith('est') && /[^aeiou]est$/.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -3) + 'e'); // 如 nicest -> nice
- }
- }
-
- // 处理副词 (-ly)
- if (lowerWord.endsWith('ly') && lowerWord.length > 2) {
- possibleBaseWords.push(lowerWord.slice(0, -2)); // 常规情况 (quickly -> quick)
-
- // 处理以辅音+y结尾变为ily的情况 (happily -> happy)
- if (lowerWord.endsWith('ily') && lowerWord.length > 3) {
- const beforeY = lowerWord.slice(0, -3);
- if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
- possibleBaseWords.push(beforeY + 'y');
- }
- }
- }
- // 处理复数形式 (-s, -es)
- if (lowerWord.endsWith('s') && lowerWord.length > 1) {
- // 基本复数形式 (books -> book)
- if (!lowerWord.endsWith('ss') && !lowerWord.endsWith('us') && !lowerWord.endsWith('is')) {
- possibleBaseWords.push(lowerWord.slice(0, -1));
- }
-
- // 处理 -es 结尾 (boxes -> box)
- if (lowerWord.endsWith('es') && lowerWord.length > 2) {
- // 处理以ch, sh, ss, x, z结尾的名词复数形式 (boxes -> box)
- if (/(?:ch|sh|ss|x|z)es$/.test(lowerWord)) {
- possibleBaseWords.push(lowerWord.slice(0, -2)); // 如 boxes -> box
- }
-
- // 处理以辅音+o结尾的名词复数形式 (heroes -> hero)
- if (lowerWord.endsWith('oes') && lowerWord.length > 3) {
- possibleBaseWords.push(lowerWord.slice(0, -2)); // 如 heroes -> hero
- }
-
- // 处理以y结尾变为ies的情况 (cities -> city)
- if (lowerWord.endsWith('ies') && lowerWord.length > 3) {
- const beforeY = lowerWord.slice(0, -3);
- if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
- possibleBaseWords.push(beforeY + 'y');
- }
- }
- }
- }
-
- // 处理以fe结尾变为ves的情况 (knives -> knife)
- if (lowerWord.endsWith('ves') && lowerWord.length > 4) {
- possibleBaseWords.push(lowerWord.slice(0, -3) + 'fe'); // 如 knives -> knife
- possibleBaseWords.push(lowerWord.slice(0, -3) + 'f'); // 如 wives -> wife
- }
-
- // 处理特殊的复数形式
- if (lowerWord.endsWith('men') && lowerWord.length > 3) {
- possibleBaseWords.push(lowerWord.slice(0, -3) + 'man'); // 如 women -> woman, men -> man
- }
- if (lowerWord.endsWith('ice') && lowerWord.length > 3) {
- possibleBaseWords.push(lowerWord.slice(0, -3) + 'ouse'); // 如 mice -> mouse
- }
- if (lowerWord.endsWith('eet') && lowerWord.length > 3) {
- possibleBaseWords.push(lowerWord.slice(0, -3) + 'oot'); // 如 feet -> foot
- }
- if (lowerWord.endsWith('ildren') && lowerWord.length > 6) {
- possibleBaseWords.push(lowerWord.slice(0, -6) + 'ild'); // 如 children -> child
- }
-
- // 去重并过滤掉过短的单词
- const uniqueBaseWords = [...new Set(possibleBaseWords)].filter(w => w.length >= 1);
-
- // 添加所有可能的原形到变形集合中
- uniqueBaseWords.forEach(base => allForms.add(base));
-
- // 判断词性的简单启发式规则
- const adjectiveSuffixes = ['ful', 'ous', 'ive', 'ic', 'al', 'ent', 'ant', 'able', 'ible', 'ary', 'ory', 'ish'];
- const verbSuffixes = ['ize', 'ise', 'ate', 'ify', 'en'];
- const nounSuffixes = ['tion', 'sion', 'ment', 'ness', 'ity', 'hood', 'ship', 'dom', 'ism', 'ist'];
- const adverbSuffixes = ['ly', 'ward', 'wise']; // 副词后缀
- // 一些常见的形容词
- const commonAdjectives = ['good', 'bad', 'big', 'small', 'high', 'low', 'long', 'short', 'old', 'new',
- 'fast', 'slow', 'hard', 'soft', 'hot', 'cold', 'warm', 'cool', 'rich', 'poor',
- 'thick', 'thin', 'wide', 'narrow', 'deep', 'shallow', 'strong', 'weak', 'young',
- 'bright', 'dark', 'light', 'heavy', 'easy', 'clean', 'dirty',
- 'full', 'empty', 'dry', 'wet', 'sick', 'healthy', 'loud', 'quiet', 'sweet',
- 'sour', 'bitter', 'nice', 'mean', 'kind', 'cruel', 'brave', 'afraid', 'happy',
- 'sad', 'angry', 'calm', 'busy', 'free', 'cheap', 'expensive', 'safe', 'dangerous'];
-
- // 一些常见的动词
- const commonVerbs = ['go', 'come', 'get', 'give', 'make', 'take', 'put', 'set', 'let', 'run', 'move',
- 'walk', 'talk', 'look', 'see', 'hear', 'feel', 'think', 'know', 'find', 'want',
- 'need', 'use', 'try', 'ask', 'work', 'call', 'help', 'play', 'stop', 'start',
- 'turn', 'show', 'tell', 'say', 'write', 'read', 'sing', 'eat', 'drink', 'sleep',
- 'sit', 'stand', 'lie', 'fall', 'rise', 'leave', 'reach', 'like', 'love', 'hate',
- 'hope', 'live', 'die', 'buy', 'sell', 'pay', 'build', 'break', 'cut', 'open', 'close'];
-
- // 检查是否是形容词
- let isLikelyAdjective = adjectiveSuffixes.some(suffix => lowerWord.endsWith(suffix)) ||
- commonAdjectives.includes(lowerWord) ||
- (lowerWord.length <= 6 && !nounSuffixes.some(suffix => lowerWord.endsWith(suffix)));
- // 检查是否是动词
- let isLikelyVerb = verbSuffixes.some(suffix => lowerWord.endsWith(suffix)) ||
- commonVerbs.includes(lowerWord) ||
- (lowerWord.length <= 5 && !adjectiveSuffixes.some(suffix => lowerWord.endsWith(suffix)) &&
- !nounSuffixes.some(suffix => lowerWord.endsWith(suffix)));
- // 检查是否是副词
- let isLikelyAdverb = adverbSuffixes.some(suffix => lowerWord.endsWith(suffix));
-
- // 动词变形 (如果可能是动词)
- if (isLikelyVerb && lowerWord.length >= 2) {
- // 第三人称单数 (walk -> walks)
- if (!lowerWord.endsWith('s') && !lowerWord.endsWith('sh') && !lowerWord.endsWith('ch') && !lowerWord.endsWith('x') && !lowerWord.endsWith('z')) {
- if (lowerWord.endsWith('s') || lowerWord.endsWith('x') || lowerWord.endsWith('ch') || lowerWord.endsWith('sh') || lowerWord.endsWith('z')) {
- allForms.add(lowerWord + 'es');
- } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
- allForms.add(lowerWord.slice(0, -1) + 'ies');
- } else {
- allForms.add(lowerWord + 's');
- }
- }
-
- // 第三人称单数 (-s)
- if (!lowerWord.endsWith('s') && !lowerWord.endsWith('sh') && !lowerWord.endsWith('ch') && !lowerWord.endsWith('x') && !lowerWord.endsWith('z')) {
- if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
- allForms.add(lowerWord.slice(0, -1) + 'ies');
- } else if (lowerWord.endsWith('s') || lowerWord.endsWith('x') || lowerWord.endsWith('ch') || lowerWord.endsWith('sh') || lowerWord.endsWith('z')) {
- allForms.add(lowerWord + 'es');
- } else {
- allForms.add(lowerWord + 's');
- }
- }
-
- // 过去式和过去分词 (-ed)
- // 不对已经以-ed结尾的词添加-ed
- if (!lowerWord.endsWith('ed')) {
- if (lowerWord.endsWith('e')) {
- allForms.add(lowerWord + 'd');
- } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
- allForms.add(lowerWord.slice(0, -1) + 'ied');
- // 确保以-ied结尾的单词也能生成其他变形
- if (lowerWord === 'study') {
- allForms.add('studies');
- allForms.add('studying');
- }
- } else if (lowerWord.length > 2 &&
- !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 1)) &&
- ['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2)) &&
- !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 3))) {
- // 双写末尾辅音字母的情况,如 stop -> stopped
- allForms.add(lowerWord + lowerWord.charAt(lowerWord.length - 1) + 'ed');
- } else {
- allForms.add(lowerWord + 'ed');
- }
- }
-
- // 现在分词 (-ing)
- // 不对已经以-ing结尾的词添加-ing
- if (!lowerWord.endsWith('ing')) {
- if (lowerWord.endsWith('ie')) {
- allForms.add(lowerWord.slice(0, -2) + 'ying');
- } else if (lowerWord.endsWith('e') && lowerWord.length > 2) {
- allForms.add(lowerWord.slice(0, -1) + 'ing');
- } else if (lowerWord.length > 2 &&
- !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 1)) &&
- ['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2)) &&
- !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 3))) {
- // 双写末尾辅音字母的情况,如 run -> running
- allForms.add(lowerWord + lowerWord.charAt(lowerWord.length - 1) + 'ing');
- } else {
- allForms.add(lowerWord + 'ing');
- }
-
- // 确保以-ied结尾的单词也能生成现在分词
- if (lowerWord.endsWith('ied') && lowerWord.length > 3) {
- allForms.add(lowerWord.slice(0, -3) + 'ying');
- }
- }
- }
-
- // 形容词和副词变形 (如果可能是形容词或副词)
- if ((isLikelyAdjective || isLikelyAdverb) && lowerWord.length >= 2 &&
- !lowerWord.endsWith('ing') && !lowerWord.endsWith('ed') &&
- lowerWord.length <= 12) { // 限制长度,避免生成不必要的变形
-
- // 检查是否是多音节形容词,这些通常使用 more/most 而不是 -er/-est
- const isMultisyllabic = lowerWord.length > 7 ||
- lowerWord.endsWith('ful') ||
- lowerWord.endsWith('ous') ||
- lowerWord.endsWith('ive') ||
- lowerWord.endsWith('ic') ||
- lowerWord.endsWith('al') ||
- lowerWord.endsWith('ent') ||
- lowerWord.endsWith('ant') ||
- lowerWord.endsWith('able') ||
- lowerWord.endsWith('ible');
-
- // 只为短形容词生成比较级和最高级
- if (!isMultisyllabic) {
- // 比较级 (-er)
- if (!lowerWord.endsWith('er')) {
- if (lowerWord.endsWith('e')) {
- allForms.add(lowerWord + 'r');
- } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
- allForms.add(lowerWord.slice(0, -1) + 'ier');
- } else if (lowerWord.length > 2 &&
- !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 1)) &&
- ['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2)) &&
- !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 3))) {
- // 双写末尾辅音字母的情况,如 big -> bigger
- allForms.add(lowerWord + lowerWord.charAt(lowerWord.length - 1) + 'er');
- } else {
- allForms.add(lowerWord + 'er');
- }
- }
-
- // 最高级 (-est)
- if (!lowerWord.endsWith('est')) {
- if (lowerWord.endsWith('e')) {
- allForms.add(lowerWord + 'st');
- } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
- allForms.add(lowerWord.slice(0, -1) + 'iest');
- } else if (lowerWord.length > 2 &&
- !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 1)) &&
- ['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2)) &&
- !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 3))) {
- // 双写末尾辅音字母的情况,如 big -> biggest
- allForms.add(lowerWord + lowerWord.charAt(lowerWord.length - 1) + 'est');
- } else {
- allForms.add(lowerWord + 'est');
- }
- }
- }
-
- // 副词变形 (-ly),只为真正的形容词生成副词形式
- if (isLikelyAdjective && !lowerWord.endsWith('ly')) {
- if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
- allForms.add(lowerWord.slice(0, -1) + 'ily');
- } else if (lowerWord.endsWith('le') && lowerWord.length > 2) {
- allForms.add(lowerWord.slice(0, -2) + 'ly');
- } else {
- allForms.add(lowerWord + 'ly');
- }
- }
- }
-
- // 名词复数形式 (对大多数单词都适用)
- if (lowerWord.length >= 2 && !lowerWord.endsWith('ing') && !lowerWord.endsWith('ed') && !lowerWord.endsWith('er') && !lowerWord.endsWith('est')) {
- if (!lowerWord.endsWith('s') && !lowerWord.endsWith('sh') && !lowerWord.endsWith('ch') && !lowerWord.endsWith('x') && !lowerWord.endsWith('z')) {
- if (lowerWord.endsWith('s') || lowerWord.endsWith('x') || lowerWord.endsWith('ch') || lowerWord.endsWith('sh') || lowerWord.endsWith('z')) {
- allForms.add(lowerWord + 'es');
- } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
- allForms.add(lowerWord.slice(0, -1) + 'ies');
- } else if (lowerWord.endsWith('f')) {
- allForms.add(lowerWord.slice(0, -1) + 'ves');
- } else if (lowerWord.endsWith('fe')) {
- allForms.add(lowerWord.slice(0, -2) + 'ves');
- } else {
- allForms.add(lowerWord + 's');
- }
- }
- }
-
- // 过滤掉不合理的变形
- const result = [...allForms].filter(form => {
- // 过滤掉长度小于1的变形
- if (form.length < 1) return false;
-
- // 过滤掉明显不合理的变形
- if (form.includes('lyly') || form.includes('erer') || form.includes('estest') ||
- form.includes('seds') || form.includes('ingsing') || form.includes('restrest') ||
- form.includes('sly') && form.length > 4 && form.endsWith('sly') && !form.endsWith('asily')) {
- return false;
- }
-
- // 过滤掉一些明显错误的变形
- if (form.endsWith('wently') || form.endsWith('wents') || form.endsWith('bett') || form.endsWith('bette') ||
- form.endsWith('betterrest') || form.endsWith('betterly') ||
- form.endsWith('childrens') || form.endsWith('childrenned') || form.endsWith('childrenning') ||
- form.endsWith('walke') || form.endsWith('plann') || form.endsWith('planne') ||
- form.endsWith('us') || form.endsWith('studi') || form.endsWith('knive') || form.endsWith('knif') ||
- form.endsWith('micer') || form.endsWith('micest') || form.endsWith('micely') || form.endsWith('mices') || form.endsWith('miced') || form.endsWith('micing') ||
- form.endsWith('quicklier') || form.endsWith('quickliest') || form.endsWith('quicklies') ||
- form.endsWith('happilier') || form.endsWith('happiliest') || form.endsWith('happilies') ||
- form.endsWith('bookser') || form.endsWith('booksest') || form.endsWith('booksly') ||
- form.endsWith('booksed') || form.endsWith('booksing') ||
- form.endsWith('citieser') || form.endsWith('citiesest') || form.endsWith('citiesly') ||
- form.endsWith('knivesser') || form.endsWith('knivessest') || form.endsWith('knivesly') ||
- form.endsWith('citi') || form.endsWith('citie') ||
- form.endsWith('fasterrest') || form.endsWith('fasterly') ||
- form.endsWith('faste') || form.endsWith('usedding') || form.endsWith('runn') || form.endsWith('runne') ||
- form.endsWith('runned') || form.endsWith('runnest') || form.endsWith('runly') ||
- form.endsWith('bigged') || form.endsWith('bigging') || form.endsWith('bigly') ||
- form.endsWith('comput') || form.endsWith('beautifuls')) {
- return false;
- }
-
- // 特殊单词的错误变形过滤
- if (lowerWord === 'better' && (form === 'bet' || form === 'bette')) {
- return false;
- }
-
- if (lowerWord === 'mice' && (form !== 'mice' && form !== 'mouse')) {
- return false;
- }
-
- if (lowerWord === 'cannot' && (form !== 'cannot' && form !== 'can' && form !== 'could' && form !== "can't")) {
- return false;
- }
-
- if ((lowerWord === 'happier' || lowerWord === 'happiest' || lowerWord === 'happily') && form === 'happi') {
- return false;
- }
-
- return true;
- });
-
- return result;
- },
-
- /**
- * 检查单词是否符合特定的变形规则
- * @param {string} word - 要检查的单词
- * @param {string} base - 基本形式
- * @returns {boolean} - 是否符合变形规则
- */
- checkSpecialWordForms(word, base) {
- // 使用 getWordAllForms 获取基本形式的所有可能变形
- const baseForms = this.getWordAllForms(base);
- if (baseForms.includes(word)) {
- return true;
- }
-
- // 反向检查:如果 word 是基本形式,base 是变形
- const wordForms = this.getWordAllForms(word);
- if (wordForms.includes(base)) {
- return true;
- }
-
- return false;
- },
- /**
- * 按照权重概率分配返回字符串
- * @param {Object} options - 包含字符串和对应权重的对象
- * @example
- * // 返回 'ali-Moonshot-Kimi-K2-Instruct' 的概率为 40%,返回 'doubao-kimi-k2-250711' 的概率为 60%
- * stringUtils.weightedRandom({
- * 'ali-Moonshot-Kimi-K2-Instruct': 40,
- * 'doubao-kimi-k2-250711': 60
- * });
- * @returns {string} - 根据权重随机选择的字符串
- */
- weightedRandom(options) {
- // 计算权重总和
- const weights = Object.values(options);
- const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
-
- // 生成一个随机数,范围是 [0, totalWeight)
- const random = Math.random() * totalWeight;
-
- // 根据随机数和权重分布选择结果
- let cumulativeWeight = 0;
- for (const [item, weight] of Object.entries(options)) {
- cumulativeWeight += weight;
- if (random < cumulativeWeight) {
- return item;
- }
- }
-
- // 如果出现意外情况,返回第一个选项
- return Object.keys(options)[0];
- }
- }
|