stringClass.js 67 KB

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