stringClass.js 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688
  1. 'use strict';
  2. import moment from 'moment';
  3. import os from 'os';
  4. import iconv from 'iconv-lite';
  5. /**
  6. * 字符串工具类集合
  7. *
  8. * 提供各种字符串处理功能,包括:
  9. * - 字符串补零、修剪空格
  10. * - 引号转义与替换
  11. * - 子字符串截取
  12. * - 全量字符串替换
  13. * - 数字/中文/英文验证
  14. * - IP地址处理
  15. * - 时间格式化
  16. * - 年级计算
  17. * - 哈希表实现
  18. * - 金额格式化
  19. * - 数组排序
  20. * - 循环熔断
  21. * - 英语单词提取
  22. *
  23. * 所有方法均为静态工具方法,可直接调用。
  24. */
  25. /**
  26. * 字符串工具类集合,提供多种字符串处理功能
  27. *
  28. * @namespace stringUtils
  29. * @property {Function} AddZero - 给字符串左侧补零
  30. * @property {Function} Trim - 删除字符串两端的空格
  31. * @property {Function} LTrim - 删除字符串左侧的空格
  32. * @property {Function} RTrim - 删除字符串右侧的空格
  33. * @property {Function} AddSingleQuotes - 转义单引号
  34. * @property {Function} SubStr - 截取子字符串
  35. * @property {Function} ReplaceSingleQuotes - 替换单引号为双单引号
  36. * @property {Function} ReplaceDoubleQuotes - 替换双引号为中文引号
  37. * @property {Function} ReplaceAllString - 替换字符串中所有匹配项
  38. * @property {Function} IsNumber - 判断字符串是否为纯数字
  39. * @property {Function} GetServerIP - 获取服务器IP地址
  40. * @property {Function} IsArray - 判断对象是否为数组
  41. * @property {Function} ExportExcelRes - 设置Excel导出的响应头
  42. * @property {Function} SetEncode - 字符编码转换
  43. * @property {Function} SetDecode - 字符解码
  44. * @property {Function} ChangeXML - 将JSON转换为XML格式
  45. * @property {Function} Random - 生成指定范围内的随机整数
  46. * @property {Function} RandomArray - 随机打乱数组顺序
  47. * @property {Function} RemoveJSONNull - 移除JSON数组中的null值
  48. * @property {Function} GetDateTimeFormat - 人性化时间格式化
  49. * @property {Function} GetGrade - 根据生日计算年级
  50. * @property {Function} GetGrade2 - 根据年级数字返回对应年级名称
  51. * @property {Function} getMinuteSecond - 将秒数转换为分钟/秒格式
  52. * @property {Function} FormatMoney - 将金额转换为格式化字符串
  53. * @property {Function} FormatPercentageToFigure - 将百分比转换为数字
  54. * @property {Function} SortArrayByStringLength - 根据字符串长度排序数组
  55. * @property {Function} HasChinese - 判断整句是否包含中文
  56. * @property {Function} SentenceChinesePosition - 返回句中中文的位置
  57. * @property {Function} IsChinese - 判断是否是中文
  58. * @property {Function} IsEnglish - 判断是否是英文
  59. * @property {Function} loopBreaker - 循环熔断函数
  60. * @property {Function} getGroupName - 获取小组名称
  61. * @property {Function} CheckIsArray - 检查是否为数组
  62. * @property {Function} GetOrdinalPostfix - 获取序数后缀
  63. * @property {Function} TrimEndZero - 去除数字末尾多余的0
  64. * @property {Function} IsValidIP - 验证IP地址格式
  65. * @property {Function} IsValidChineseNumberParentheses - 验证字符串是否只包含汉字、数字、字母和括号
  66. * @property {Function} GetClientIP - 获取客户端真实IP地址
  67. * @property {Function} cleanWord - 清理单词中的非字母字符
  68. * @property {Function} extractEnglishWords - 从文本中提取英语单词
  69. */
  70. // 不规则动词映射
  71. const irregularVerbs = {
  72. 'arise': ['arose', 'arisen', 'arising', 'arises'],
  73. 'awake': ['awoke', 'awoken', 'awaking', 'awakes'],
  74. 'backslide': ['backslid', 'backslidden', 'backsliding', 'backslides'],
  75. 'become': ['became', 'become', 'becoming', 'becomes'], // 已有,但确保完整
  76. 'behold': ['beheld', 'beholding', 'beholds'],
  77. 'bend': ['bent', 'bending', 'bends'],
  78. 'bet': ['bet', 'betting', 'bets'],
  79. 'bid': ['bid', 'bidding', 'bids'],
  80. 'bind': ['bound', 'binding', 'binds'],
  81. 'bleed': ['bled', 'bleeding', 'bleeds'],
  82. 'blow': ['blew', 'blown', 'blowing', 'blows'],
  83. 'break': ['broke', 'broken', 'breaking', 'breaks'],
  84. 'breed': ['bred', 'breeding', 'breeds'],
  85. 'bring': ['brought', 'bringing', 'brings'],
  86. 'build': ['built', 'building', 'builds'],
  87. 'burn': ['burnt', 'burned', 'burning', 'burns'],
  88. 'burst': ['burst', 'bursting', 'bursts'],
  89. 'buy': ['bought', 'buying', 'buys'],
  90. 'cast': ['cast', 'casting', 'casts'],
  91. 'catch': ['caught', 'catching', 'catches'],
  92. 'choose': ['chose', 'chosen', 'choosing', 'chooses'],
  93. 'cling': ['clung', 'clinging', 'clings'],
  94. 'come': ['came', 'coming', 'comes'],
  95. 'cost': ['cost', 'costing', 'costs'],
  96. 'creep': ['crept', 'creeping', 'creeps'],
  97. 'cut': ['cut', 'cutting', 'cuts'],
  98. 'deal': ['dealt', 'dealing', 'deals'],
  99. 'dig': ['dug', 'digging', 'digs'],
  100. 'dive': ['dove', 'dived', 'diving', 'dives'],
  101. 'do': ['did', 'done', 'doing', 'does'],
  102. 'draw': ['drew', 'drawn', 'drawing', 'draws'],
  103. 'dream': ['dreamt', 'dreamed', 'dreaming', 'dreams'],
  104. 'drink': ['drank', 'drunk', 'drinking', 'drinks'],
  105. 'drive': ['drove', 'driven', 'driving', 'drives'],
  106. 'eat': ['ate', 'eaten', 'eating', 'eats'],
  107. 'fall': ['fell', 'fallen', 'falling', 'falls'],
  108. 'feed': ['fed', 'feeding', 'feeds'],
  109. 'feel': ['felt', 'feeling', 'feels'],
  110. 'fight': ['fought', 'fighting', 'fights'],
  111. 'find': ['found', 'finding', 'finds'],
  112. 'fit': ['fit', 'fitted', 'fitting', 'fits'],
  113. 'flee': ['fled', 'fleeing', 'flees'],
  114. 'fling': ['flung', 'flinging', 'flings'],
  115. 'fly': ['flew', 'flown', 'flying', 'flies'],
  116. 'forbid': ['forbade', 'forbidden', 'forbidding', 'forbids'],
  117. 'forget': ['forgot', 'forgotten', 'forgetting', 'forgets'],
  118. 'forgive': ['forgave', 'forgiven', 'forgiving', 'forgives'],
  119. 'freeze': ['froze', 'frozen', 'freezing', 'freezes'],
  120. 'get': ['got', 'gotten', 'getting', 'gets'],
  121. 'give': ['gave', 'given', 'giving', 'gives'],
  122. 'go': ['went', 'gone', 'going', 'goes'],
  123. 'grind': ['ground', 'grinding', 'grinds'],
  124. 'grow': ['grew', 'grown', 'growing', 'grows'],
  125. 'hang': ['hung', 'hanging', 'hangs'],
  126. 'have': ['has', 'had', 'having'],
  127. 'hear': ['heard', 'hearing', 'hears'],
  128. 'hide': ['hid', 'hidden', 'hiding', 'hides'],
  129. 'hit': ['hit', 'hitting', 'hits'],
  130. 'hold': ['held', 'holding', 'holds'],
  131. 'hurt': ['hurt', 'hurting', 'hurts'],
  132. 'keep': ['kept', 'keeping', 'keeps'],
  133. 'kneel': ['knelt', 'kneeling', 'kneels'],
  134. 'know': ['knew', 'known', 'knowing', 'knows'],
  135. 'lay': ['laid', 'laying', 'lays'],
  136. 'lead': ['led', 'leading', 'leads'],
  137. 'lean': ['leant', 'leaning', 'leans'],
  138. 'leap': ['leapt', 'leaping', 'leaps'],
  139. 'learn': ['learnt', 'learned', 'learning', 'learns'],
  140. 'leave': ['left', 'leaving', 'leaves'],
  141. 'lend': ['lent', 'lending', 'lends'],
  142. 'let': ['let', 'letting', 'lets'],
  143. 'lie': ['lay', 'lain', 'lying', 'lies'],
  144. 'light': ['lit', 'lighting', 'lights'],
  145. 'lose': ['lost', 'losing', 'loses'],
  146. 'make': ['made', 'making', 'makes'],
  147. 'mean': ['meant', 'meaning', 'means'],
  148. 'meet': ['met', 'meeting', 'meets'],
  149. 'mistake': ['mistook', 'mistaken', 'mistaking', 'mistakes'],
  150. 'pay': ['paid', 'paying', 'pays'],
  151. 'put': ['put', 'putting', 'puts'],
  152. 'quit': ['quit', 'quitting', 'quits'],
  153. 'read': ['read', 'reading', 'reads'],
  154. 'ride': ['rode', 'ridden', 'riding', 'rides'],
  155. 'ring': ['rang', 'rung', 'ringing', 'rings'],
  156. 'rise': ['rose', 'risen', 'rising', 'rises'],
  157. 'run': ['ran', 'run', 'running', 'runs'],
  158. 'say': ['said', 'saying', 'says'],
  159. 'see': ['saw', 'seen', 'seeing', 'sees'],
  160. 'seek': ['sought', 'seeking', 'seeks'],
  161. 'sell': ['sold', 'selling', 'sells'],
  162. 'send': ['sent', 'sending', 'sends'],
  163. 'set': ['set', 'setting', 'sets'],
  164. 'shake': ['shook', 'shaken', 'shaking', 'shakes'],
  165. 'shed': ['shed', 'shedding', 'sheds'],
  166. 'shine': ['shone', 'shining', 'shines'],
  167. 'shoot': ['shot', 'shooting', 'shoots'],
  168. 'show': ['showed', 'shown', 'showing', 'shows'],
  169. 'shrink': ['shrank', 'shrunk', 'shrinking', 'shrinks'],
  170. 'shut': ['shut', 'shutting', 'shuts'],
  171. 'sing': ['sang', 'sung', 'singing', 'sings'],
  172. 'sink': ['sank', 'sunk', 'sinking', 'sinks'],
  173. 'sit': ['sat', 'sitting', 'sits'],
  174. 'sleep': ['slept', 'sleeping', 'sleeps'],
  175. 'slide': ['slid', 'sliding', 'slides'],
  176. 'sling': ['slung', 'slinging', 'slings'],
  177. 'slink': ['slunk', 'slinking', 'slinks'],
  178. 'smell': ['smelt', 'smelling', 'smells'],
  179. 'speak': ['spoke', 'spoken', 'speaking', 'speaks'],
  180. 'speed': ['sped', 'speeding', 'speeds'],
  181. 'spell': ['spelt', 'spelling', 'spells'],
  182. 'spend': ['spent', 'spending', 'spends'],
  183. 'spill': ['spilt', 'spilling', 'spills'],
  184. 'spin': ['spun', 'spinning', 'spins'],
  185. 'spit': ['spat', 'spitting', 'spits'],
  186. 'split': ['split', 'splitting', 'splits'],
  187. 'spread': ['spread', 'spreading', 'spreads'],
  188. 'spring': ['sprang', 'sprung', 'springing', 'springs'],
  189. 'stand': ['stood', 'standing', 'stands'],
  190. 'steal': ['stole', 'stolen', 'stealing', 'steals'],
  191. 'stick': ['stuck', 'sticking', 'sticks'],
  192. 'sting': ['stung', 'stinging', 'stings'],
  193. 'stink': ['stank', 'stunk', 'stinking', 'stinks'],
  194. 'strike': ['struck', 'striking', 'strikes'],
  195. 'strive': ['strove', 'striven', 'striving', 'strives'],
  196. 'swear': ['swore', 'sworn', 'swearing', 'swears'],
  197. 'sweep': ['swept', 'sweeping', 'sweeps'],
  198. 'swim': ['swam', 'swum', 'swimming', 'swims'],
  199. 'swing': ['swung', 'swinging', 'swings'],
  200. 'take': ['took', 'taken', 'taking', 'takes'],
  201. 'teach': ['taught', 'teaching', 'teaches'],
  202. 'tear': ['tore', 'torn', 'tearing', 'tears'],
  203. 'tell': ['told', 'telling', 'tells'],
  204. 'think': ['thought', 'thinking', 'thinks'],
  205. 'throw': ['threw', 'thrown', 'throwing', 'throws'],
  206. 'thrust': ['thrust', 'thrusting', 'thrusts'],
  207. 'tread': ['trod', 'trodden', 'treading', 'treads'],
  208. 'undergo': ['underwent', 'undergone', 'undergoing', 'undergoes'],
  209. 'understand': ['understood', 'understanding', 'understands'],
  210. 'undertake': ['undertook', 'undertaken', 'undertaking', 'undertakes'],
  211. 'upset': ['upset', 'upsetting', 'upsets'],
  212. 'wake': ['woke', 'woken', 'waking', 'wakes'],
  213. 'wear': ['wore', 'worn', 'wearing', 'wears'],
  214. 'weave': ['wove', 'woven', 'weaving', 'weaves'],
  215. 'weep': ['wept', 'weeping', 'weeps'],
  216. 'win': ['won', 'winning', 'wins'],
  217. 'wind': ['wound', 'winding', 'winds'],
  218. 'withdraw': ['withdrew', 'withdrawn', 'withdrawing', 'withdraws'],
  219. 'wring': ['wrung', 'wringing', 'wrings']
  220. };
  221. // 不规则形容词/副词映射表
  222. const irregularAdjectives = {
  223. 'good': ['better', 'best'],
  224. 'bad': ['worse', 'worst'],
  225. 'many': ['more', 'most'],
  226. 'much': ['more', 'most'],
  227. 'little': ['less', 'least'],
  228. 'far': ['further', 'furthest', 'farther', 'farthest'],
  229. 'old': ['older', 'oldest', 'elder', 'eldest'],
  230. 'late': ['later', 'latest', 'latter', 'last'],
  231. 'well': ['better', 'best'],
  232. 'ill': ['worse', 'worst'],
  233. 'easy': ['easier', 'easiest'],
  234. 'happy': ['happier', 'happiest'],
  235. 'busy': ['busier', 'busiest'],
  236. 'pretty': ['prettier', 'prettiest'],
  237. 'heavy': ['heavier', 'heaviest'],
  238. 'simple': ['simpler', 'simplest'],
  239. 'clever': ['cleverer', 'cleverest'],
  240. 'narrow': ['narrower', 'narrowest'],
  241. 'quiet': ['quieter', 'quietest'],
  242. 'large': ['larger', 'largest'],
  243. 'small': ['smaller', 'smallest'],
  244. 'big': ['bigger', 'biggest'],
  245. 'hot': ['hotter', 'hottest'],
  246. 'tall': ['taller', 'tallest'],
  247. 'short': ['shorter', 'shortest'],
  248. 'long': ['longer', 'longest'],
  249. 'high': ['higher', 'highest'],
  250. 'low': ['lower', 'lowest'],
  251. 'deep': ['deeper', 'deepest'],
  252. 'wide': ['wider', 'widest'],
  253. 'near': ['nearer', 'nearest'],
  254. 'clean': ['cleaner', 'cleanest'],
  255. 'quick': ['quicker', 'quickest'],
  256. 'slow': ['slower', 'slowest'],
  257. 'strong': ['stronger', 'strongest'],
  258. 'weak': ['weaker', 'weakest'],
  259. 'young': ['younger', 'youngest'],
  260. 'rich': ['richer', 'richest'],
  261. 'poor': ['poorer', 'poorest'],
  262. 'thick': ['thicker', 'thickest'],
  263. 'thin': ['thinner', 'thinnest'],
  264. 'fast': ['faster', 'fastest'],
  265. 'hard': ['harder', 'hardest'],
  266. 'soft': ['softer', 'softest'],
  267. 'warm': ['warmer', 'warmest'],
  268. 'cool': ['cooler', 'coolest'],
  269. 'cold': ['colder', 'coldest'],
  270. 'bright': ['brighter', 'brightest'],
  271. 'dark': ['darker', 'darkest'],
  272. 'light': ['lighter', 'lightest'],
  273. 'loud': ['louder', 'loudest'],
  274. 'sweet': ['sweeter', 'sweetest'],
  275. 'sour': ['sourer', 'sourest'],
  276. 'bitter': ['bitterer', 'bitterest'],
  277. 'nice': ['nicer', 'nicest'],
  278. 'fine': ['finer', 'finest'],
  279. 'brave': ['braver', 'bravest'],
  280. 'calm': ['calmer', 'calmest'],
  281. 'cute': ['cuter', 'cutest'],
  282. 'fair': ['fairer', 'fairest'],
  283. 'fresh': ['fresher', 'freshest'],
  284. 'full': ['fuller', 'fullest'],
  285. 'glad': ['gladder', 'gladdest'],
  286. 'great': ['greater', 'greatest'],
  287. 'kind': ['kinder', 'kindest'],
  288. 'new': ['newer', 'newest'],
  289. 'odd': ['odder', 'oddest'],
  290. 'rare': ['rarer', 'rarest'],
  291. 'real': ['realer', 'realest'],
  292. 'safe': ['safer', 'safest'],
  293. 'same': ['samer', 'samest'],
  294. 'sure': ['surer', 'surest'],
  295. 'true': ['truer', 'truest'],
  296. 'wise': ['wiser', 'wisest']
  297. };
  298. // 特殊不规则名词复数形式
  299. const irregularNouns = {
  300. 'child': ['children'],
  301. 'man': ['men'],
  302. 'woman': ['women'],
  303. 'foot': ['feet'],
  304. 'tooth': ['teeth'],
  305. 'goose': ['geese'],
  306. 'mouse': ['mice'],
  307. 'ox': ['oxen'],
  308. 'person': ['people'],
  309. 'louse': ['lice'],
  310. 'leaf': ['leaves'],
  311. 'life': ['lives'],
  312. 'knife': ['knives'],
  313. 'wife': ['wives'],
  314. 'half': ['halves'],
  315. 'wolf': ['wolves'],
  316. 'shelf': ['shelves'],
  317. 'self': ['selves'],
  318. 'calf': ['calves'],
  319. 'thief': ['thieves'],
  320. 'deer': ['deer'],
  321. 'sheep': ['sheep'],
  322. 'fish': ['fish'],
  323. 'series': ['series'],
  324. 'species': ['species'],
  325. 'aircraft': ['aircraft'],
  326. 'information': ['information'],
  327. 'money': ['money'],
  328. 'rice': ['rice'],
  329. 'equipment': ['equipment'],
  330. 'furniture': ['furniture'],
  331. 'datum': ['data'],
  332. 'phenomenon': ['phenomena'],
  333. 'criterion': ['criteria']
  334. };
  335. export const stringUtils = {
  336. // 导出不规则字典
  337. irregularVerbs,
  338. irregularAdjectives,
  339. irregularNouns,
  340. //给字符串左侧补零
  341. AddZero: (str, length) => {
  342. while (str.length < length) {
  343. str = `0${str}`;
  344. }
  345. return str;
  346. },
  347. //删除左右两端的空格
  348. Trim: (str) => str.replace(/(^\s*)|(\s*$)/g, ""),
  349. //删除左边的空格
  350. LTrim: (str) => str.replace(/(^\s*)/g, ""),
  351. //删除右边的空格
  352. RTrim: (str) => str.replace(/(\s*$)/g, ""),
  353. //转义单引号
  354. AddSingleQuotes: (str) => str.replace(/'/g, "''"),
  355. //截取子字符串
  356. SubStr: (str, start, length) => (!str || str === "") ? str : str.substr(start, length),
  357. //替换单引号
  358. ReplaceSingleQuotes: (str) => str.replace(/'/g, "''"),
  359. //替换双引号
  360. ReplaceDoubleQuotes: (str) => {
  361. if (str && str.length > 0) {
  362. do {
  363. str = str.replace("\"", "“");
  364. str = str.replace("\"", "”");
  365. } while (str.indexOf("\"") >= 0);
  366. }
  367. return str;
  368. },
  369. //替换字符串中所有匹配项
  370. ReplaceAllString: (str, replaceStrFrom, replaceStrTo) => {
  371. if (str && str.length > 0) {
  372. const reg = new RegExp(replaceStrFrom, "g");
  373. return str.toString().replace(reg, replaceStrTo);
  374. }
  375. return str;
  376. },
  377. //判断是否是数字,true:是,false:不是
  378. IsNumber: (value) => /^\d+$/.test(value),
  379. //获取服务器IP地址
  380. GetServerIP: () => {
  381. const interfaces = os.networkInterfaces();
  382. for (const devName in interfaces) {
  383. const iface = interfaces[devName];
  384. for (let i = 0; i < iface.length; i++) {
  385. const alias = iface[i];
  386. if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
  387. return alias.address;
  388. }
  389. }
  390. }
  391. },
  392. //判断是否是数组
  393. IsArray: (obj) => Object.prototype.toString.call(obj) === '[object Array]',
  394. //导出Excel的Res
  395. ExportExcelRes: (res, fileName) => {
  396. res.set({
  397. //'Content-Type': 'application/vnd.ms-execl;charset=utf-8',
  398. 'Content-Type': 'application/vnd.ms-execl',
  399. 'Content-Disposition': "attachment;filename=" + encodeURIComponent(fileName),
  400. 'Pragma': 'no-cache',
  401. 'Expires': 0
  402. });
  403. return res;
  404. },
  405. //转码
  406. SetEncode: (content, encode) => {
  407. const buffer = Buffer.from(content);
  408. return iconv.encode(buffer, encode);
  409. },
  410. //解码
  411. SetDecode: (content, encode) => {
  412. const buffer = Buffer.from(content);
  413. return iconv.decode(buffer, encode);
  414. },
  415. //将JSON转换为XML格式
  416. ChangeXML: (json) => {
  417. const result = [];
  418. result.push("<xml>\r\n");
  419. for (const item in json) {
  420. result.push(`<${item}>`);
  421. result.push(json[item]);
  422. result.push(`</${item}>\r\n`);
  423. }
  424. result.push("</xml>");
  425. return result.join("");
  426. },
  427. //生成指定范围内的随机整数
  428. Random: (start, end) => {
  429. const result = parseInt(Math.random() * (end - start + 1) + start);
  430. return result;
  431. },
  432. //随机打乱数组顺序(使用Fisher-Yates算法变体)
  433. RandomArray: (arr) => {
  434. const arrResult = [];
  435. let maxCount = 0;
  436. do {
  437. const rnd = stringUtils.Random(0, arr.length - 1);
  438. if (arr[rnd]) {
  439. arrResult.push(arr[rnd]);
  440. arr[rnd] = null;
  441. }
  442. maxCount++;
  443. } while (arrResult.length < arr.length && maxCount < 10000);
  444. return arrResult;
  445. },
  446. //移除JSON数组中的null值
  447. RemoveJSONNull: (list) => {
  448. for (let i = 0; i < list.length; i++) {
  449. const item = list[i];
  450. for (const key in item) {
  451. if (item[key] == null) {
  452. delete item[key];
  453. }
  454. }
  455. }
  456. return list;
  457. },
  458. //得到格式化的时间为更人性化的刚刚,几分钟前,几小时前等
  459. //人性化时间格式化(使用moment.js)
  460. GetDateTimeFormat: (date) => {
  461. let result = "";
  462. const time1 = moment(date);
  463. const today = moment(`${moment().format('YYYY-MM-DD')} 00:00:00`);
  464. const yesterday = moment(`${moment().add(-1, 'd').format('YYYY-MM-DD')} 00:00:00`);
  465. const yesterday2 = moment(`${moment().add(-2, 'd').format('YYYY-MM-DD')} 00:00:00`);
  466. const tomorrow = moment(`${moment().add(1, 'd').format('YYYY-MM-DD')} 00:00:00`);
  467. const tomorrow2 = moment(`${moment().add(2, 'd').format('YYYY-MM-DD')} 00:00:00`);
  468. if (time1 < tomorrow) {
  469. if (moment().diff(time1, "s") < 300) {
  470. result = "刚刚";
  471. }
  472. if (time1 >= today) {
  473. result = "今天";
  474. } else if (time1 > yesterday) {
  475. result = "昨天";
  476. } else if (time1 > yesterday2) {
  477. result = "前天";
  478. } else {
  479. const daysDiff = moment().diff(time1, "d");
  480. const monthsDiff = moment().diff(time1, "M");
  481. result = monthsDiff < 1 ? `${daysDiff}天前` : `${monthsDiff}月前`;
  482. }
  483. } else {
  484. if (time1 < tomorrow2) {
  485. result = "明天";
  486. } else {
  487. const daysDiff = -moment().diff(time1, "d");
  488. const monthsDiff = -moment().diff(time1, "M");
  489. result = monthsDiff < 1
  490. ? `${daysDiff < 2 ? 2 : daysDiff}天后`
  491. : `${monthsDiff}月后`;
  492. }
  493. }
  494. return result;
  495. },
  496. //得到年级
  497. //根据生日计算年级
  498. GetGrade: (birthday, returnType) => {
  499. if (birthday.includes(".")) {
  500. birthday = birthday.replace(".", "-");
  501. }
  502. let result = "";
  503. if (birthday) {
  504. const b = moment(birthday);
  505. const now = moment();
  506. const diff = now.diff(b, 'months');
  507. if (returnType === "number") {
  508. if (diff <= 85) result = 1;
  509. else if (diff <= 97) result = 2;
  510. else if (diff <= 109) result = 3;
  511. else result = 4;
  512. } else {
  513. if (diff <= 37) {
  514. result = `${diff}个月`;
  515. } else if (diff <= 49) {
  516. result = "幼儿园小班";
  517. } else if (diff <= 61) {
  518. result = "幼儿园中班";
  519. } else if (diff <= 73) {
  520. result = "幼儿园大班";
  521. } else if (diff <= 85) {
  522. result = "一年级";
  523. } else if (diff <= 97) {
  524. result = "二年级";
  525. } else if (diff <= 109) {
  526. result = "三年级";
  527. } else if (diff <= 121) {
  528. result = "四年级";
  529. } else if (diff <= 133) {
  530. result = "五年级";
  531. } else if (diff <= 145) {
  532. result = "六年级";
  533. } else if (diff > 145) {
  534. result = "初中及以上年龄";
  535. }
  536. }
  537. }
  538. return result;
  539. },
  540. //得到年级
  541. //根据年级数字返回对应年级名称
  542. GetGrade2: (gradeNum) => {
  543. let result = "一年级";
  544. switch (gradeNum) {
  545. case 0:
  546. case 1:
  547. result = "一年级";
  548. break;
  549. case 2:
  550. result = "二年级";
  551. break;
  552. case 3:
  553. result = "三年级";
  554. break;
  555. case 4:
  556. result = "四年级";
  557. break;
  558. case 5:
  559. result = "五年级";
  560. break;
  561. case 6:
  562. result = "六年级";
  563. break;
  564. case 7:
  565. result = "初一";
  566. break;
  567. case 8:
  568. result = "初二";
  569. break;
  570. case 9:
  571. result = "初三";
  572. break;
  573. case 10:
  574. result = "高一";
  575. break;
  576. case 11:
  577. result = "高二";
  578. break;
  579. case 12:
  580. result = "高三";
  581. break;
  582. default:
  583. result = "大学及成人";
  584. break;
  585. }
  586. return result;
  587. },
  588. //将秒数转换为分钟/秒格式
  589. getMinuteSecond: (second, chs, hasSecond) => {
  590. if (!second) second = 0;
  591. const secondUnit = chs ? "秒" : "″";
  592. const minuteUnit = chs ? "分" : "′";
  593. const hourUnit = chs ? "时" : ":";
  594. if (second < 60) {
  595. return `${second}${secondUnit}`;
  596. }
  597. let minute = Math.floor(second / 60);
  598. second = Math.round((second - minute * 60) * 1000) / 1000;
  599. if (minute >= 60) {
  600. const hour = Math.floor(minute / 60);
  601. minute = minute - hour * 60;
  602. if (minute === 0 && second === 0) {
  603. return `${hour}${hourUnit}`;
  604. } else if (second === 0) {
  605. return `${hour}${hourUnit}${minute}${minuteUnit}`;
  606. } else {
  607. return hasSecond
  608. ? `${hour}${hourUnit}${minute + 1}${minuteUnit}`
  609. : `${hour}${hourUnit}${minute}${minuteUnit}${second}${secondUnit}`;
  610. }
  611. } else {
  612. if (second === 0) {
  613. return `${minute}${minuteUnit}`;
  614. } else {
  615. return hasSecond
  616. ? `${minute + 1}${minuteUnit}`
  617. : `${minute}${minuteUnit}${second}${secondUnit}`;
  618. }
  619. }
  620. },
  621. //哈希表的类
  622. HashTable: class HashTable {
  623. constructor() {
  624. this.size = 0;
  625. this.entry = {};
  626. }
  627. add(key, value) {
  628. if (!this.containsKey(key)) {
  629. this.size++;
  630. }
  631. this.entry[key] = value;
  632. }
  633. update(key, value) {
  634. if (this.containsKey(key)) {
  635. this.entry[key] = value;
  636. }
  637. }
  638. getValue(key) {
  639. return this.containsKey(key) ? this.entry[key] : null;
  640. }
  641. remove(key) {
  642. if (this.containsKey(key) && (delete this.entry[key])) {
  643. this.size--;
  644. }
  645. }
  646. containsKey(key) {
  647. return (key in this.entry);
  648. }
  649. containsValue(value) {
  650. for (const prop in this.entry) {
  651. if (this.entry[prop] == value) {
  652. return true;
  653. }
  654. }
  655. return false;
  656. }
  657. getValues() {
  658. const values = [];
  659. for (const prop in this.entry) {
  660. values.push(this.entry[prop]);
  661. }
  662. return values;
  663. }
  664. getKeys() {
  665. const keys = [];
  666. for (const prop in this.entry) {
  667. keys.push(prop);
  668. }
  669. return keys;
  670. }
  671. getKeysAndValues() {
  672. const keysValues = [];
  673. for (const prop in this.entry) {
  674. keysValues.push(prop + "###" + this.entry[prop]);
  675. }
  676. return keysValues;
  677. }
  678. getSize() {
  679. return this.size;
  680. }
  681. clear() {
  682. this.size = 0;
  683. this.entry = {};
  684. }
  685. },
  686. //将金额转换为格式化字符串(保留两位小数)
  687. FormatMoney: (money) => {
  688. if (money === 0) return "0.00";
  689. let result = (Math.round(money) / 100).toString();
  690. if (result.includes(".")) {
  691. if (result.substr(result.indexOf(".")).length < 3) {
  692. result += "0";
  693. }
  694. } else {
  695. result += ".00";
  696. }
  697. return result;
  698. },
  699. FormatPercentageToFigure: (percentage) => {
  700. let result;
  701. if (percentage.indexOf("%") > 0) {
  702. result = percentage.replace("%", "");
  703. }
  704. result = Number(result) / 100;
  705. return result;
  706. },
  707. //排序数组根据字符串长度
  708. SortArrayByStringLength: (arr) => {
  709. const result = [];
  710. const temp = [];
  711. for (let i = 0; i < 30; i++) {
  712. temp.push([]);
  713. }
  714. for (let i = 0; i < arr.length; i++) {
  715. const item = arr[i];
  716. temp[item.length].push(item);
  717. }
  718. for (let i = 0; i < temp.length; i++) {
  719. temp[i].sort();
  720. for (let j = 0; j < temp[i].length; j++) {
  721. result.push(temp[i][j]);
  722. }
  723. }
  724. return result;
  725. },
  726. //返回句中中文的位置
  727. SentenceChinesePosition: (temp) => {
  728. let result = -1;
  729. const reg = /^[\u4e00-\u9fa5]|[\uFE30-\uFFA0]+$/; /*定义验证表达式*/
  730. if (temp) {
  731. temp = temp.toString();
  732. for (let i = 0; i < temp.length; i++) {
  733. if (reg.test(temp[i])) {
  734. result = i;
  735. break;
  736. }
  737. }
  738. }
  739. return result;
  740. },
  741. //判断整句是否有中文
  742. HasChinese: (temp) => {
  743. let result = false;
  744. const reg = /^[\u4e00-\u9fa5]|[\uFE30-\uFFA0]+$/; /*定义验证表达式*/
  745. if (temp) {
  746. temp = temp.toString();
  747. for (let i = 0; i < temp.length; i++) {
  748. if (reg.test(temp[i])) {
  749. result = true;
  750. break;
  751. }
  752. }
  753. }
  754. return result;
  755. },
  756. //判断是否是中文
  757. IsChinese: (temp) => {
  758. const reg = /^[\u4e00-\u9fa5\uFE30-\uFFA0]+$/; /*定义验证表达式*/
  759. return reg.test(temp); /*进行验证*/
  760. },
  761. //判断是否是英文
  762. IsEnglish: (temp) => {
  763. const reg = new RegExp("^[A-Za-z]+(?:['-][A-Za-z]+)*(?:\\s+[A-Za-z]+(?:['-][A-Za-z]+)*)*$");
  764. return reg.test(temp); /*进行验证*/
  765. },
  766. GetProgramSource: (str) => {
  767. switch (str) {
  768. case 98:
  769. return "拼音";
  770. case 99:
  771. return "拼读";
  772. case 106:
  773. return "识字";
  774. case 105:
  775. return "计算";
  776. case 164:
  777. return "口算";
  778. case 166:
  779. return "秒过";
  780. case 186:
  781. return "语境";
  782. case 173:
  783. return "分数线";
  784. case 90:
  785. return "专注力";
  786. case 0:
  787. return "";
  788. default:
  789. return str;
  790. }
  791. },
  792. //循环熔断函数
  793. loopBreaker: (startTime, second) => {
  794. if (!second) {
  795. second = 60;
  796. }
  797. if (!startTime) {
  798. startTime = Date.now();
  799. }
  800. if (Date.now() - startTime > second * 1000) {
  801. throw new Error("Loop Broken!");
  802. }
  803. },
  804. //得到小组名称
  805. getGroupName: (groupID, isAllName) => {
  806. let name = "";
  807. switch (groupID) {
  808. case 1:
  809. name = '彩';
  810. if (isAllName) {
  811. name = "彩虹";
  812. }
  813. break;
  814. case 2:
  815. name = '润';
  816. if (isAllName) {
  817. name = "润雨";
  818. }
  819. break;
  820. case 3:
  821. name = '扬';
  822. if (isAllName) {
  823. name = "扬帆";
  824. }
  825. break;
  826. }
  827. return name;
  828. },
  829. CheckIsArray: (obj) => {
  830. return Object.prototype.toString.call(obj) === '[object Array]';
  831. },
  832. //得到序数的后缀
  833. GetOrdinalPostfix: (number) => {
  834. switch (number) {
  835. case 1:
  836. return "st";
  837. case 2:
  838. return "nd";
  839. case 3:
  840. return "rd";
  841. default:
  842. return "th";
  843. }
  844. },
  845. //去除数字末尾多余的0
  846. TrimEndZero: (input)=> {
  847. // 判断是否是数字或数字字符串
  848. if (typeof input === 'number' || (typeof input === 'string' && /^-?\d+(\.\d+)?$/.test(input))) {
  849. // 转换为数字后转为字符串输出,自动去除末尾多余的0
  850. return Number(input).toString();
  851. }
  852. // 非数字或非数字字符串保持原样返回
  853. return input;
  854. },
  855. // 验证IP地址格式是否有效
  856. IsValidIP: (ip) => {
  857. if (!ip) return false;
  858. // IPv4格式验证
  859. const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
  860. if (ipv4Regex.test(ip)) {
  861. const parts = ip.split('.');
  862. return parts.every(part => {
  863. const num = parseInt(part, 10);
  864. return num >= 0 && num <= 255;
  865. });
  866. }
  867. // IPv6格式验证(简化版)
  868. const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
  869. return ipv6Regex.test(ip);
  870. },
  871. // 判断字符串是否只包含汉字、数字、大小写字母和全/半角小括号
  872. IsValidChineseNumberParentheses: (str) => {
  873. if (!str) return true; // 空字符串视为有效
  874. // 匹配规则:
  875. // [\u4e00-\u9fa5]: 匹配汉字
  876. // 0-9: 匹配数字
  877. // a-zA-Z: 匹配大小写字母
  878. // (): 匹配半角小括号
  879. // (): 匹配全角小括号
  880. const regex = /^[\u4e00-\u9fa5\da-zA-Z()()]+$/;
  881. return regex.test(str);
  882. },
  883. // 获取客户端真实IP地址的通用函数
  884. GetClientIP: (ctx) => {
  885. const request = ctx?.request || ctx;
  886. const headers = request?.headers || {};
  887. const socket = request?.socket || ctx?.socket || ctx?.req?.socket;
  888. // 检查所有可能的代理头
  889. const proxyHeaders = [
  890. 'x-forwarded-for',
  891. 'x-real-ip',
  892. 'x-client-ip',
  893. 'x-forwarded',
  894. 'forwarded-for',
  895. 'x-cluster-client-ip',
  896. 'proxy-client-ip',
  897. 'cf-connecting-ip', // Cloudflare
  898. 'true-client-ip', // Akamai and Cloudflare
  899. 'fastly-client-ip', // Fastly
  900. 'x-original-forwarded-for'
  901. ];
  902. let clientIP = null;
  903. // 1. 首先检查所有代理头
  904. for (const header of proxyHeaders) {
  905. const value = headers[header];
  906. if (value) {
  907. // 处理可能的多个IP地址(取第一个,通常是最原始的客户端IP)
  908. clientIP = value.split(',')[0].trim();
  909. if (stringUtils.IsValidIP(clientIP)) {
  910. break;
  911. }
  912. }
  913. }
  914. // 2. 如果没有找到有效的代理头IP,尝试Koa的标准方法
  915. if (!clientIP || !stringUtils.IsValidIP(clientIP)) {
  916. clientIP = ctx?.ip || request?.ip;
  917. }
  918. // 3. 如果还是没有,尝试socket
  919. if (!clientIP || !stringUtils.IsValidIP(clientIP)) {
  920. clientIP = socket?.remoteAddress;
  921. }
  922. // 处理IPv6格式
  923. if (clientIP) {
  924. // 处理IPv4映射的IPv6地址 (::ffff:127.0.0.1 格式)
  925. if (clientIP.startsWith('::ffff:')) {
  926. clientIP = clientIP.substring(7);
  927. }
  928. // 处理IPv6本地回环地址
  929. else if (clientIP === '::1') {
  930. clientIP = '127.0.0.1';
  931. }
  932. }
  933. return clientIP || '0.0.0.0';
  934. },
  935. cleanWord(word) {
  936. if (!word) return '';
  937. // 去除单词前后的非字母字符
  938. const cleaned = word.replace(/^[^A-Za-z]+|[^A-Za-z]+$/g, '');
  939. // 保留单词中间的撇号和连字符
  940. return cleaned.replace(/[^A-Za-z''-]/g, '');
  941. },
  942. // 提取英语单词的函数 - 增强版
  943. extractEnglishWords(texts) {
  944. //console.group('英语单词提取');
  945. const words = new Set();
  946. texts.forEach(item => {
  947. const text = item;
  948. //console.log('处理文本:', text);
  949. // 使用多种分隔符分割文本(空格、逗号、句号、感叹号、中文字符等)
  950. // 这个正则表达式会匹配任何非英文字母、撇号或连字符的字符作为分隔符
  951. const parts = text.split(/[^A-Za-z''-]+/).filter(Boolean);
  952. //console.log('分割后的部分:', parts);
  953. // 处理每个可能的单词
  954. parts.forEach(part => {
  955. // 清理并验证单词
  956. const cleanWord = this.cleanWord(part);
  957. // 特殊处理单词"I"
  958. if (cleanWord === 'I' || cleanWord === 'a') {
  959. words.add(cleanWord); // 添加小写的"i"
  960. //console.log('添加单词: I (特殊处理)');
  961. }
  962. // 处理其他单词(长度>=2)
  963. else if (cleanWord && cleanWord.length >= 2 && /^[A-Za-z''-]+$/.test(cleanWord)) {
  964. let lowerWord = cleanWord.toLowerCase();
  965. if (lowerWord=="i'm"){
  966. lowerWord="I'm";
  967. }
  968. words.add(lowerWord);
  969. //console.log('添加单词:', lowerWord);
  970. }
  971. });
  972. });
  973. //const result = Array.from(words).sort();
  974. let result = Array.from(words);
  975. //console.log('提取结果:', result);
  976. //console.groupEnd();
  977. return result;
  978. },
  979. /**
  980. * 获取单词的所有变形形式
  981. * @param {string} word - 要获取变形的单词
  982. * @returns {string[]} - 单词的所有变形形式数组
  983. */
  984. getWordAllForms: (word) => {
  985. if (!word || typeof word !== 'string') {
  986. return [];
  987. }
  988. word = word.trim();
  989. if (word === '') {
  990. return [];
  991. }
  992. // 保留原始单词,包括大小写和标点符号
  993. const originalWord = word;
  994. // 转换为小写进行处理
  995. const lowerWord = word.toLowerCase();
  996. // 使用Set存储所有可能的变形,避免重复
  997. const allForms = new Set([lowerWord]); // 初始包含原单词
  998. // 如果原始单词与小写形式不同,也添加原始单词
  999. if (originalWord !== lowerWord) {
  1000. allForms.add(originalWord);
  1001. }
  1002. // 检查是否是不规则形容词/副词
  1003. for (const [base, forms] of Object.entries(stringUtils.irregularAdjectives)) {
  1004. if (base === lowerWord || forms.includes(lowerWord)) {
  1005. // 添加原形和所有变形
  1006. allForms.add(base);
  1007. forms.forEach(form => allForms.add(form));
  1008. // 不规则形容词处理完成后直接返回,避免进一步处理
  1009. return [...allForms];
  1010. }
  1011. }
  1012. // 检查是否是不规则动词
  1013. for (const [base, forms] of Object.entries(stringUtils.irregularVerbs)) {
  1014. if (base === lowerWord || forms.includes(lowerWord)) {
  1015. // 添加原形和所有变形
  1016. allForms.add(base);
  1017. forms.forEach(form => allForms.add(form));
  1018. // 不规则动词处理完成后直接返回,避免进一步处理
  1019. return [...allForms];
  1020. }
  1021. }
  1022. // 不规则名词检查(单数形式)
  1023. if (stringUtils.irregularNouns[lowerWord]) {
  1024. allForms.add(lowerWord); // 添加原词
  1025. stringUtils.irregularNouns[lowerWord].forEach(form => allForms.add(form));
  1026. // 不规则名词处理完成后直接返回,避免进一步处理
  1027. return [...allForms];
  1028. }
  1029. // 不规则名词检查(复数形式)
  1030. for (const [singular, plurals] of Object.entries(stringUtils.irregularNouns)) {
  1031. if (plurals.includes(lowerWord)) {
  1032. allForms.add(singular);
  1033. allForms.add(lowerWord); // 添加原词
  1034. plurals.forEach(form => allForms.add(form));
  1035. // 不规则名词处理完成后直接返回,避免进一步处理
  1036. return [...allForms];
  1037. }
  1038. }
  1039. // 特殊处理一些常见的副词和特殊单词,避免错误的词干提取和变形
  1040. const specialWords = {
  1041. // 情态动词
  1042. 'can': ['can', 'could', 'cannot', "can't"],
  1043. 'may': ['may', 'might'],
  1044. 'shall': ['shall', 'should', "shouldn't"],
  1045. 'will': ['will', 'would', "won't", "wouldn't"],
  1046. 'must': ['must', 'have to', 'has to', 'had to', "mustn't"],
  1047. // 特殊形容词及其变形
  1048. 'good': ['good', 'better', 'best', 'well'],
  1049. 'bad': ['bad', 'worse', 'worst', 'badly'],
  1050. 'better': ['better', 'good', 'best', 'well'],
  1051. 'best': ['best', 'good', 'better', 'well'],
  1052. 'worse': ['worse', 'bad', 'worst', 'badly'],
  1053. 'worst': ['worst', 'bad', 'worse', 'badly'],
  1054. // 特殊副词
  1055. 'early': ['early', 'earlier', 'earliest'],
  1056. 'only': ['only'],
  1057. 'likely': ['likely', 'more likely', 'most likely'],
  1058. 'friendly': ['friendly', 'friendlier', 'friendliest'],
  1059. 'lovely': ['lovely', 'lovelier', 'loveliest'],
  1060. 'timely': ['timely', 'timelier', 'timeliest'],
  1061. 'weekly': ['weekly'],
  1062. 'monthly': ['monthly'],
  1063. 'yearly': ['yearly'],
  1064. 'daily': ['daily'],
  1065. 'well': ['well', 'better', 'best', 'good'],
  1066. 'badly': ['badly', 'worse', 'worst', 'bad'], // 对应bad的副词形式
  1067. // 特殊动词
  1068. 'play': ['play', 'plays', 'played', 'playing'],
  1069. 'stay': ['stay', 'stays', 'stayed', 'staying'],
  1070. 'pay': ['pay', 'pays', 'paid', 'paying'],
  1071. 'lay': ['lay', 'lays', 'laid', 'laying'],
  1072. 'say': ['say', 'says', 'said', 'saying'],
  1073. 'go': ['go', 'goes', 'went', 'gone', 'going'],
  1074. 'went': ['went', 'go', 'gone', 'going', 'goes'],
  1075. // 特殊名词
  1076. 'box': ['box', 'boxes'],
  1077. 'fox': ['fox', 'foxes'],
  1078. 'tax': ['tax', 'taxes'],
  1079. 'child': ['child', 'children'],
  1080. 'children': ['children', 'child'],
  1081. 'bush': ['bush', 'bushes'],
  1082. 'dish': ['dish', 'dishes'],
  1083. 'church': ['church', 'churches'],
  1084. 'tomato': ['tomato', 'tomatoes'],
  1085. 'potato': ['potato', 'potatoes'],
  1086. 'hero': ['hero', 'heroes'],
  1087. 'echo': ['echo', 'echoes'],
  1088. // 缩写词
  1089. 'its': ['its'], // 物主代词
  1090. 'it\'s': ['it\'s', 'it is', 'it has'], // it is 的缩写
  1091. 'I\'m': ['I\'m', 'I am'], // I am 的缩写
  1092. 'don\'t': ['don\'t', 'do not'], // do not 的缩写
  1093. 'doesn\'t': ['doesn\'t', 'does not'], // does not 的缩写
  1094. 'can\'t': ['can\'t', 'cannot'], // can not 的缩写
  1095. 'won\'t': ['won\'t', 'will not'], // will not 的缩写
  1096. 'we\'re': ['we are'],
  1097. 'they\'re': ['they are'],
  1098. 'you\'re': ['you are'],
  1099. 'he\'s': ['he is', 'he has'],
  1100. 'she\'s': ['she is', 'she has'],
  1101. 'it\'d': ['it would', 'it had'],
  1102. 'we\'d': ['we would', 'we had'],
  1103. 'they\'d': ['they would', 'they had'],
  1104. 'couldn\'t': ['could not'],
  1105. 'shouldn\'t': ['should not'],
  1106. 'wouldn\'t': ['would not'],
  1107. 'mustn\'t': ['must not'],
  1108. 'haven\'t': ['haven\'t', 'have not'],
  1109. 'hasn\'t': ['hasn\'t', 'has not'],
  1110. 'hadn\'t': ['hadn\'t', 'had not'],
  1111. 'isn\'t': ['isn\'t', 'is not'],
  1112. 'aren\'t': ['aren\'t', 'are not'],
  1113. 'wasn\'t': ['wasn\'t', 'was not'],
  1114. 'weren\'t': ['weren\'t', 'were not'],
  1115. 'should\'ve': ['should have'],
  1116. 'would\'ve': ['would have'],
  1117. 'could\'ve': ['could have']
  1118. };
  1119. // 如果是特殊单词,添加预定义的变形
  1120. if (specialWords[lowerWord]) {
  1121. specialWords[lowerWord].forEach(form => allForms.add(form));
  1122. // 处理完特殊词后返回,避免进一步处理
  1123. return [...allForms];
  1124. }
  1125. // 检查是否是特殊单词的变形
  1126. for (const [base, forms] of Object.entries(specialWords)) {
  1127. if (forms.includes(lowerWord)) {
  1128. // 添加基本形式
  1129. allForms.add(base);
  1130. // 添加所有变形
  1131. forms.forEach(form => allForms.add(form));
  1132. // 找到特殊单词变形后直接返回,避免进一步处理
  1133. return [...allForms];
  1134. }
  1135. }
  1136. // 获取单词的原形(基本形式)
  1137. const possibleBaseWords = [];
  1138. // 特殊单词列表,这些单词不应被识别为任何变形
  1139. const specialBaseWords = ['this', 'is', 'was', 'has', 'his', 'its', 'us', 'yes', 'thus', 'plus'];
  1140. if (specialBaseWords.includes(lowerWord)) {
  1141. // 对于特殊基础词,只返回原词
  1142. return [lowerWord];
  1143. }
  1144. // 处理规则变形
  1145. // 处理过去式/过去分词 (-ed)
  1146. if (lowerWord.endsWith('ed') && lowerWord.length > 2) {
  1147. // 基本形式
  1148. possibleBaseWords.push(lowerWord.slice(0, -2)); // 常规情况 (walked -> walk)
  1149. // 处理双辅音+ed的情况 (stepped -> step, planned -> plan)
  1150. const doubleConsonantPattern = /([bcdfghjklmnpqrstvwxyz])\1ed$/;
  1151. if (doubleConsonantPattern.test(lowerWord)) {
  1152. possibleBaseWords.push(lowerWord.slice(0, -3)); // 如 planned -> plan
  1153. }
  1154. // 处理以辅音+y结尾变为ied的情况 (studied -> study)
  1155. if (lowerWord.endsWith('ied') && lowerWord.length > 3) {
  1156. const beforeY = lowerWord.slice(0, -3);
  1157. if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
  1158. possibleBaseWords.push(beforeY + 'y');
  1159. }
  1160. }
  1161. // 处理以e结尾的动词变为ed的情况 (liked -> like)
  1162. if (lowerWord.endsWith('ed') && /[bcdfghjklmnpqrstvwxyz]ed$/.test(lowerWord)) {
  1163. possibleBaseWords.push(lowerWord.slice(0, -1)); // 如 liked -> like
  1164. }
  1165. }
  1166. // 处理以e结尾的动词加d的情况 (used -> use)
  1167. if (lowerWord.endsWith('d') && !lowerWord.endsWith('ed') && lowerWord.length > 1) {
  1168. possibleBaseWords.push(lowerWord.slice(0, -1)); // 如 used -> use
  1169. }
  1170. // 处理现在分词 (-ing)
  1171. if (lowerWord.endsWith('ing') && lowerWord.length > 3) {
  1172. possibleBaseWords.push(lowerWord.slice(0, -3)); // 常规情况 (walking -> walk)
  1173. // 处理双辅音+ing的情况 (running -> run)
  1174. const doubleConsonantPattern = /([bcdfghjklmnpqrstvwxyz])\1ing$/;
  1175. if (doubleConsonantPattern.test(lowerWord)) {
  1176. possibleBaseWords.push(lowerWord.slice(0, -4)); // 如 running -> run
  1177. }
  1178. // 处理特殊的ing形式 (lying -> lie)
  1179. if (lowerWord.endsWith('ying') && lowerWord.length > 4) {
  1180. possibleBaseWords.push(lowerWord.slice(0, -4) + 'ie'); // 如 lying -> lie
  1181. }
  1182. // 处理以辅音+e结尾的动词变为ing的情况 (like -> liking)
  1183. if (lowerWord.endsWith('ing') && /[bcdfghjklmnpqrstvwxyz]ing$/.test(lowerWord)) {
  1184. possibleBaseWords.push(lowerWord.slice(0, -3) + 'e');
  1185. }
  1186. }
  1187. // 处理比较级 (-er)
  1188. if (lowerWord.endsWith('er') && lowerWord.length > 2) {
  1189. possibleBaseWords.push(lowerWord.slice(0, -2)); // 常规情况 (faster -> fast)
  1190. // 处理双辅音+er的情况 (bigger -> big)
  1191. const doubleConsonantPattern = /([bcdfghjklmnpqrstvwxyz])\1er$/;
  1192. if (doubleConsonantPattern.test(lowerWord)) {
  1193. possibleBaseWords.push(lowerWord.slice(0, -3)); // 如 bigger -> big
  1194. }
  1195. // 处理以辅音+y结尾变为ier的情况 (happier -> happy)
  1196. if (lowerWord.endsWith('ier') && lowerWord.length > 3) {
  1197. const beforeY = lowerWord.slice(0, -3);
  1198. if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
  1199. possibleBaseWords.push(beforeY + 'y');
  1200. }
  1201. }
  1202. // 处理以e结尾+r的情况 (nicer -> nice)
  1203. if (lowerWord.endsWith('er') && /[^aeiou]er$/.test(lowerWord)) {
  1204. possibleBaseWords.push(lowerWord.slice(0, -2) + 'e'); // 如 nicer -> nice
  1205. }
  1206. }
  1207. // 处理最高级 (-est)
  1208. if (lowerWord.endsWith('est') && lowerWord.length > 3) {
  1209. possibleBaseWords.push(lowerWord.slice(0, -3)); // 常规情况 (fastest -> fast)
  1210. // 处理双辅音+est的情况 (biggest -> big)
  1211. const doubleConsonantPattern = /([bcdfghjklmnpqrstvwxyz])\1est$/;
  1212. if (doubleConsonantPattern.test(lowerWord)) {
  1213. possibleBaseWords.push(lowerWord.slice(0, -4)); // 如 biggest -> big
  1214. }
  1215. // 处理以辅音+y结尾变为iest的情况 (happiest -> happy)
  1216. if (lowerWord.endsWith('iest') && lowerWord.length > 4) {
  1217. const beforeY = lowerWord.slice(0, -4);
  1218. if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
  1219. possibleBaseWords.push(beforeY + 'y');
  1220. }
  1221. }
  1222. // 处理以e结尾+st的情况 (nicest -> nice)
  1223. if (lowerWord.endsWith('est') && /[^aeiou]est$/.test(lowerWord)) {
  1224. possibleBaseWords.push(lowerWord.slice(0, -3) + 'e'); // 如 nicest -> nice
  1225. }
  1226. }
  1227. // 处理副词 (-ly)
  1228. if (lowerWord.endsWith('ly') && lowerWord.length > 2) {
  1229. possibleBaseWords.push(lowerWord.slice(0, -2)); // 常规情况 (quickly -> quick)
  1230. // 处理以辅音+y结尾变为ily的情况 (happily -> happy)
  1231. if (lowerWord.endsWith('ily') && lowerWord.length > 3) {
  1232. const beforeY = lowerWord.slice(0, -3);
  1233. if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
  1234. possibleBaseWords.push(beforeY + 'y');
  1235. }
  1236. }
  1237. }
  1238. // 处理复数形式 (-s, -es)
  1239. if (lowerWord.endsWith('s') && lowerWord.length > 1) {
  1240. // 基本复数形式 (books -> book)
  1241. if (!lowerWord.endsWith('ss') && !lowerWord.endsWith('us') && !lowerWord.endsWith('is')) {
  1242. possibleBaseWords.push(lowerWord.slice(0, -1));
  1243. }
  1244. // 处理 -es 结尾 (boxes -> box)
  1245. if (lowerWord.endsWith('es') && lowerWord.length > 2) {
  1246. // 处理以ch, sh, ss, x, z结尾的名词复数形式 (boxes -> box)
  1247. if (/(?:ch|sh|ss|x|z)es$/.test(lowerWord)) {
  1248. possibleBaseWords.push(lowerWord.slice(0, -2)); // 如 boxes -> box
  1249. }
  1250. // 处理以辅音+o结尾的名词复数形式 (heroes -> hero)
  1251. if (lowerWord.endsWith('oes') && lowerWord.length > 3) {
  1252. possibleBaseWords.push(lowerWord.slice(0, -2)); // 如 heroes -> hero
  1253. }
  1254. // 处理以y结尾变为ies的情况 (cities -> city)
  1255. if (lowerWord.endsWith('ies') && lowerWord.length > 3) {
  1256. const beforeY = lowerWord.slice(0, -3);
  1257. if (beforeY.length > 0 && /[a-z]$/.test(beforeY)) {
  1258. possibleBaseWords.push(beforeY + 'y');
  1259. }
  1260. }
  1261. }
  1262. }
  1263. // 处理以fe结尾变为ves的情况 (knives -> knife)
  1264. if (lowerWord.endsWith('ves') && lowerWord.length > 4) {
  1265. possibleBaseWords.push(lowerWord.slice(0, -3) + 'fe'); // 如 knives -> knife
  1266. possibleBaseWords.push(lowerWord.slice(0, -3) + 'f'); // 如 wives -> wife
  1267. }
  1268. // 处理特殊的复数形式
  1269. if (lowerWord.endsWith('men') && lowerWord.length > 3) {
  1270. possibleBaseWords.push(lowerWord.slice(0, -3) + 'man'); // 如 women -> woman, men -> man
  1271. }
  1272. if (lowerWord.endsWith('ice') && lowerWord.length > 3) {
  1273. possibleBaseWords.push(lowerWord.slice(0, -3) + 'ouse'); // 如 mice -> mouse
  1274. }
  1275. if (lowerWord.endsWith('eet') && lowerWord.length > 3) {
  1276. possibleBaseWords.push(lowerWord.slice(0, -3) + 'oot'); // 如 feet -> foot
  1277. }
  1278. if (lowerWord.endsWith('ildren') && lowerWord.length > 6) {
  1279. possibleBaseWords.push(lowerWord.slice(0, -6) + 'ild'); // 如 children -> child
  1280. }
  1281. // 去重并过滤掉过短的单词
  1282. const uniqueBaseWords = [...new Set(possibleBaseWords)].filter(w => w.length >= 1);
  1283. // 添加所有可能的原形到变形集合中
  1284. uniqueBaseWords.forEach(base => allForms.add(base));
  1285. // 判断词性的简单启发式规则
  1286. const adjectiveSuffixes = ['ful', 'ous', 'ive', 'ic', 'al', 'ent', 'ant', 'able', 'ible', 'ary', 'ory', 'ish'];
  1287. const verbSuffixes = ['ize', 'ise', 'ate', 'ify', 'en'];
  1288. const nounSuffixes = ['tion', 'sion', 'ment', 'ness', 'ity', 'hood', 'ship', 'dom', 'ism', 'ist'];
  1289. const adverbSuffixes = ['ly', 'ward', 'wise']; // 副词后缀
  1290. // 一些常见的形容词
  1291. const commonAdjectives = ['good', 'bad', 'big', 'small', 'high', 'low', 'long', 'short', 'old', 'new',
  1292. 'fast', 'slow', 'hard', 'soft', 'hot', 'cold', 'warm', 'cool', 'rich', 'poor',
  1293. 'thick', 'thin', 'wide', 'narrow', 'deep', 'shallow', 'strong', 'weak', 'young',
  1294. 'bright', 'dark', 'light', 'heavy', 'easy', 'clean', 'dirty',
  1295. 'full', 'empty', 'dry', 'wet', 'sick', 'healthy', 'loud', 'quiet', 'sweet',
  1296. 'sour', 'bitter', 'nice', 'mean', 'kind', 'cruel', 'brave', 'afraid', 'happy',
  1297. 'sad', 'angry', 'calm', 'busy', 'free', 'cheap', 'expensive', 'safe', 'dangerous'];
  1298. // 一些常见的动词
  1299. const commonVerbs = ['go', 'come', 'get', 'give', 'make', 'take', 'put', 'set', 'let', 'run', 'move',
  1300. 'walk', 'talk', 'look', 'see', 'hear', 'feel', 'think', 'know', 'find', 'want',
  1301. 'need', 'use', 'try', 'ask', 'work', 'call', 'help', 'play', 'stop', 'start',
  1302. 'turn', 'show', 'tell', 'say', 'write', 'read', 'sing', 'eat', 'drink', 'sleep',
  1303. 'sit', 'stand', 'lie', 'fall', 'rise', 'leave', 'reach', 'like', 'love', 'hate',
  1304. 'hope', 'live', 'die', 'buy', 'sell', 'pay', 'build', 'break', 'cut', 'open', 'close'];
  1305. // 检查是否是形容词
  1306. let isLikelyAdjective = adjectiveSuffixes.some(suffix => lowerWord.endsWith(suffix)) ||
  1307. commonAdjectives.includes(lowerWord) ||
  1308. (lowerWord.length <= 6 && !nounSuffixes.some(suffix => lowerWord.endsWith(suffix)));
  1309. // 检查是否是动词
  1310. let isLikelyVerb = verbSuffixes.some(suffix => lowerWord.endsWith(suffix)) ||
  1311. commonVerbs.includes(lowerWord) ||
  1312. (lowerWord.length <= 5 && !adjectiveSuffixes.some(suffix => lowerWord.endsWith(suffix)) &&
  1313. !nounSuffixes.some(suffix => lowerWord.endsWith(suffix)));
  1314. // 检查是否是副词
  1315. let isLikelyAdverb = adverbSuffixes.some(suffix => lowerWord.endsWith(suffix));
  1316. // 动词变形 (如果可能是动词)
  1317. if (isLikelyVerb && lowerWord.length >= 2) {
  1318. // 第三人称单数 (walk -> walks)
  1319. if (!lowerWord.endsWith('s') && !lowerWord.endsWith('sh') && !lowerWord.endsWith('ch') && !lowerWord.endsWith('x') && !lowerWord.endsWith('z')) {
  1320. if (lowerWord.endsWith('s') || lowerWord.endsWith('x') || lowerWord.endsWith('ch') || lowerWord.endsWith('sh') || lowerWord.endsWith('z')) {
  1321. allForms.add(lowerWord + 'es');
  1322. } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
  1323. allForms.add(lowerWord.slice(0, -1) + 'ies');
  1324. } else {
  1325. allForms.add(lowerWord + 's');
  1326. }
  1327. }
  1328. // 第三人称单数 (-s)
  1329. if (!lowerWord.endsWith('s') && !lowerWord.endsWith('sh') && !lowerWord.endsWith('ch') && !lowerWord.endsWith('x') && !lowerWord.endsWith('z')) {
  1330. if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
  1331. allForms.add(lowerWord.slice(0, -1) + 'ies');
  1332. } else if (lowerWord.endsWith('s') || lowerWord.endsWith('x') || lowerWord.endsWith('ch') || lowerWord.endsWith('sh') || lowerWord.endsWith('z')) {
  1333. allForms.add(lowerWord + 'es');
  1334. } else {
  1335. allForms.add(lowerWord + 's');
  1336. }
  1337. }
  1338. // 过去式和过去分词 (-ed)
  1339. // 不对已经以-ed结尾的词添加-ed
  1340. if (!lowerWord.endsWith('ed')) {
  1341. if (lowerWord.endsWith('e')) {
  1342. allForms.add(lowerWord + 'd');
  1343. } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
  1344. allForms.add(lowerWord.slice(0, -1) + 'ied');
  1345. // 确保以-ied结尾的单词也能生成其他变形
  1346. if (lowerWord === 'study') {
  1347. allForms.add('studies');
  1348. allForms.add('studying');
  1349. }
  1350. } else if (lowerWord.length > 2 &&
  1351. !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 1)) &&
  1352. ['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2)) &&
  1353. !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 3))) {
  1354. // 双写末尾辅音字母的情况,如 stop -> stopped
  1355. allForms.add(lowerWord + lowerWord.charAt(lowerWord.length - 1) + 'ed');
  1356. } else {
  1357. allForms.add(lowerWord + 'ed');
  1358. }
  1359. }
  1360. // 现在分词 (-ing)
  1361. // 不对已经以-ing结尾的词添加-ing
  1362. if (!lowerWord.endsWith('ing')) {
  1363. if (lowerWord.endsWith('ie')) {
  1364. allForms.add(lowerWord.slice(0, -2) + 'ying');
  1365. } else if (lowerWord.endsWith('e') && lowerWord.length > 2) {
  1366. allForms.add(lowerWord.slice(0, -1) + 'ing');
  1367. } else if (lowerWord.length > 2 &&
  1368. !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 1)) &&
  1369. ['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2)) &&
  1370. !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 3))) {
  1371. // 双写末尾辅音字母的情况,如 run -> running
  1372. allForms.add(lowerWord + lowerWord.charAt(lowerWord.length - 1) + 'ing');
  1373. } else {
  1374. allForms.add(lowerWord + 'ing');
  1375. }
  1376. // 确保以-ied结尾的单词也能生成现在分词
  1377. if (lowerWord.endsWith('ied') && lowerWord.length > 3) {
  1378. allForms.add(lowerWord.slice(0, -3) + 'ying');
  1379. }
  1380. }
  1381. }
  1382. // 形容词和副词变形 (如果可能是形容词或副词)
  1383. if ((isLikelyAdjective || isLikelyAdverb) && lowerWord.length >= 2 &&
  1384. !lowerWord.endsWith('ing') && !lowerWord.endsWith('ed') &&
  1385. lowerWord.length <= 12) { // 限制长度,避免生成不必要的变形
  1386. // 检查是否是多音节形容词,这些通常使用 more/most 而不是 -er/-est
  1387. const isMultisyllabic = lowerWord.length > 7 ||
  1388. lowerWord.endsWith('ful') ||
  1389. lowerWord.endsWith('ous') ||
  1390. lowerWord.endsWith('ive') ||
  1391. lowerWord.endsWith('ic') ||
  1392. lowerWord.endsWith('al') ||
  1393. lowerWord.endsWith('ent') ||
  1394. lowerWord.endsWith('ant') ||
  1395. lowerWord.endsWith('able') ||
  1396. lowerWord.endsWith('ible');
  1397. // 只为短形容词生成比较级和最高级
  1398. if (!isMultisyllabic) {
  1399. // 比较级 (-er)
  1400. if (!lowerWord.endsWith('er')) {
  1401. if (lowerWord.endsWith('e')) {
  1402. allForms.add(lowerWord + 'r');
  1403. } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
  1404. allForms.add(lowerWord.slice(0, -1) + 'ier');
  1405. } else if (lowerWord.length > 2 &&
  1406. !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 1)) &&
  1407. ['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2)) &&
  1408. !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 3))) {
  1409. // 双写末尾辅音字母的情况,如 big -> bigger
  1410. allForms.add(lowerWord + lowerWord.charAt(lowerWord.length - 1) + 'er');
  1411. } else {
  1412. allForms.add(lowerWord + 'er');
  1413. }
  1414. }
  1415. // 最高级 (-est)
  1416. if (!lowerWord.endsWith('est')) {
  1417. if (lowerWord.endsWith('e')) {
  1418. allForms.add(lowerWord + 'st');
  1419. } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
  1420. allForms.add(lowerWord.slice(0, -1) + 'iest');
  1421. } else if (lowerWord.length > 2 &&
  1422. !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 1)) &&
  1423. ['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2)) &&
  1424. !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 3))) {
  1425. // 双写末尾辅音字母的情况,如 big -> biggest
  1426. allForms.add(lowerWord + lowerWord.charAt(lowerWord.length - 1) + 'est');
  1427. } else {
  1428. allForms.add(lowerWord + 'est');
  1429. }
  1430. }
  1431. }
  1432. // 副词变形 (-ly),只为真正的形容词生成副词形式
  1433. if (isLikelyAdjective && !lowerWord.endsWith('ly')) {
  1434. if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
  1435. allForms.add(lowerWord.slice(0, -1) + 'ily');
  1436. } else if (lowerWord.endsWith('le') && lowerWord.length > 2) {
  1437. allForms.add(lowerWord.slice(0, -2) + 'ly');
  1438. } else {
  1439. allForms.add(lowerWord + 'ly');
  1440. }
  1441. }
  1442. }
  1443. // 名词复数形式 (对大多数单词都适用)
  1444. if (lowerWord.length >= 2 && !lowerWord.endsWith('ing') && !lowerWord.endsWith('ed') && !lowerWord.endsWith('er') && !lowerWord.endsWith('est')) {
  1445. if (!lowerWord.endsWith('s') && !lowerWord.endsWith('sh') && !lowerWord.endsWith('ch') && !lowerWord.endsWith('x') && !lowerWord.endsWith('z')) {
  1446. if (lowerWord.endsWith('s') || lowerWord.endsWith('x') || lowerWord.endsWith('ch') || lowerWord.endsWith('sh') || lowerWord.endsWith('z')) {
  1447. allForms.add(lowerWord + 'es');
  1448. } else if (lowerWord.endsWith('y') && !['a', 'e', 'i', 'o', 'u'].includes(lowerWord.charAt(lowerWord.length - 2))) {
  1449. allForms.add(lowerWord.slice(0, -1) + 'ies');
  1450. } else if (lowerWord.endsWith('f')) {
  1451. allForms.add(lowerWord.slice(0, -1) + 'ves');
  1452. } else if (lowerWord.endsWith('fe')) {
  1453. allForms.add(lowerWord.slice(0, -2) + 'ves');
  1454. } else {
  1455. allForms.add(lowerWord + 's');
  1456. }
  1457. }
  1458. }
  1459. // 过滤掉不合理的变形
  1460. const result = [...allForms].filter(form => {
  1461. // 过滤掉长度小于1的变形
  1462. if (form.length < 1) return false;
  1463. // 过滤掉明显不合理的变形
  1464. if (form.includes('lyly') || form.includes('erer') || form.includes('estest') ||
  1465. form.includes('seds') || form.includes('ingsing') || form.includes('restrest') ||
  1466. form.includes('sly') && form.length > 4 && form.endsWith('sly') && !form.endsWith('asily')) {
  1467. return false;
  1468. }
  1469. // 过滤掉一些明显错误的变形
  1470. if (form.endsWith('wently') || form.endsWith('wents') || form.endsWith('bett') || form.endsWith('bette') ||
  1471. form.endsWith('betterrest') || form.endsWith('betterly') ||
  1472. form.endsWith('childrens') || form.endsWith('childrenned') || form.endsWith('childrenning') ||
  1473. form.endsWith('walke') || form.endsWith('plann') || form.endsWith('planne') ||
  1474. form.endsWith('us') || form.endsWith('studi') || form.endsWith('knive') || form.endsWith('knif') ||
  1475. form.endsWith('micer') || form.endsWith('micest') || form.endsWith('micely') || form.endsWith('mices') || form.endsWith('miced') || form.endsWith('micing') ||
  1476. form.endsWith('quicklier') || form.endsWith('quickliest') || form.endsWith('quicklies') ||
  1477. form.endsWith('happilier') || form.endsWith('happiliest') || form.endsWith('happilies') ||
  1478. form.endsWith('bookser') || form.endsWith('booksest') || form.endsWith('booksly') ||
  1479. form.endsWith('booksed') || form.endsWith('booksing') ||
  1480. form.endsWith('citieser') || form.endsWith('citiesest') || form.endsWith('citiesly') ||
  1481. form.endsWith('knivesser') || form.endsWith('knivessest') || form.endsWith('knivesly') ||
  1482. form.endsWith('citi') || form.endsWith('citie') ||
  1483. form.endsWith('fasterrest') || form.endsWith('fasterly') ||
  1484. form.endsWith('faste') || form.endsWith('usedding') || form.endsWith('runn') || form.endsWith('runne') ||
  1485. form.endsWith('runned') || form.endsWith('runnest') || form.endsWith('runly') ||
  1486. form.endsWith('bigged') || form.endsWith('bigging') || form.endsWith('bigly') ||
  1487. form.endsWith('comput') || form.endsWith('beautifuls')) {
  1488. return false;
  1489. }
  1490. // 特殊单词的错误变形过滤
  1491. if (lowerWord === 'better' && (form === 'bet' || form === 'bette')) {
  1492. return false;
  1493. }
  1494. if (lowerWord === 'mice' && (form !== 'mice' && form !== 'mouse')) {
  1495. return false;
  1496. }
  1497. if (lowerWord === 'cannot' && (form !== 'cannot' && form !== 'can' && form !== 'could' && form !== "can't")) {
  1498. return false;
  1499. }
  1500. if ((lowerWord === 'happier' || lowerWord === 'happiest' || lowerWord === 'happily') && form === 'happi') {
  1501. return false;
  1502. }
  1503. return true;
  1504. });
  1505. return result;
  1506. },
  1507. /**
  1508. * 检查单词是否符合特定的变形规则
  1509. * @param {string} word - 要检查的单词
  1510. * @param {string} base - 基本形式
  1511. * @returns {boolean} - 是否符合变形规则
  1512. */
  1513. checkSpecialWordForms(word, base) {
  1514. // 使用 getWordAllForms 获取基本形式的所有可能变形
  1515. const baseForms = this.getWordAllForms(base);
  1516. if (baseForms.includes(word)) {
  1517. return true;
  1518. }
  1519. // 反向检查:如果 word 是基本形式,base 是变形
  1520. const wordForms = this.getWordAllForms(word);
  1521. if (wordForms.includes(base)) {
  1522. return true;
  1523. }
  1524. return false;
  1525. },
  1526. /**
  1527. * 按照权重概率分配返回字符串
  1528. * @param {Object} options - 包含字符串和对应权重的对象
  1529. * @example
  1530. * // 返回 'ali-Moonshot-Kimi-K2-Instruct' 的概率为 40%,返回 'doubao-kimi-k2-250711' 的概率为 60%
  1531. * stringUtils.weightedRandom({
  1532. * 'ali-Moonshot-Kimi-K2-Instruct': 40,
  1533. * 'doubao-kimi-k2-250711': 60
  1534. * });
  1535. * @returns {string} - 根据权重随机选择的字符串
  1536. */
  1537. weightedRandom(options) {
  1538. // 计算权重总和
  1539. const weights = Object.values(options);
  1540. const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
  1541. // 生成一个随机数,范围是 [0, totalWeight)
  1542. const random = Math.random() * totalWeight;
  1543. // 根据随机数和权重分布选择结果
  1544. let cumulativeWeight = 0;
  1545. for (const [item, weight] of Object.entries(options)) {
  1546. cumulativeWeight += weight;
  1547. if (random < cumulativeWeight) {
  1548. return item;
  1549. }
  1550. }
  1551. // 如果出现意外情况,返回第一个选项
  1552. return Object.keys(options)[0];
  1553. }
  1554. }