Skip to content

Commit

Permalink
feat: Add try/catch for dynimac import
Browse files Browse the repository at this point in the history
  • Loading branch information
hotoo committed Nov 20, 2023
1 parent cd46352 commit 90886a2
Showing 1 changed file with 39 additions and 35 deletions.
74 changes: 39 additions & 35 deletions src/segment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,46 +9,50 @@ let hansIntlSegmenter: any; // Intl.Segmenter
* 分词并标注词性。
*/
export function segment(hans: string, segment?: IPinyinSegment): string[] {
// @node-rs/jieba (Rust)
if (segment === "@node-rs/jieba") {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { load, cut /*, tag */ } = require("@node-rs/jieba");
if (!nodeRsJiebaLoaded) {
nodeRsJiebaLoaded = true;
load();
try {
// @node-rs/jieba (Rust)
if (segment === "@node-rs/jieba") {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { load, cut /*, tag */ } = require("@node-rs/jieba");
if (!nodeRsJiebaLoaded) {
nodeRsJiebaLoaded = true;
load();
}
return cut(hans, false);
// return tag(hans);
}
return cut(hans, false);
// return tag(hans);
}

// segmentit (Node.js)
if (segment === "segmentit") {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { Segment, useDefault } = require("segmentit");
if (!segmentit) {
segmentit = useDefault(new Segment());
// segmentit (Node.js)
if (segment === "segmentit") {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { Segment, useDefault } = require("segmentit");
if (!segmentit) {
segmentit = useDefault(new Segment());
}
return segmentit.doSegment(hans, {
simple: true,
});
}
return segmentit.doSegment(hans, {
simple: true,
});
}

// Intl.Segmenter
if (segment === "Intl.Segmenter") {
if (typeof Intl?.Segmenter === "function") {
if (!hansIntlSegmenter) {
hansIntlSegmenter = new Intl.Segmenter("zh-Hans-CN", {
granularity: "word",
});
// Intl.Segmenter
if (segment === "Intl.Segmenter") {
if (typeof Intl?.Segmenter === "function") {
if (!hansIntlSegmenter) {
hansIntlSegmenter = new Intl.Segmenter("zh-Hans-CN", {
granularity: "word",
});
}
return [...hansIntlSegmenter.segment(hans)].map((s) => s.segment);
}
return [...hansIntlSegmenter.segment(hans)].map((s) => s.segment);
}
}

// eslint-disable-next-line @typescript-eslint/no-var-requires
const nodejieba = require("nodejieba");
// 默认使用 nodejieba (C++)
// return nodejieba.tag(hans);
// nodejieba 定义的类型返回值错误,先忽略。
return nodejieba.cutSmall(hans, 4) as unknown as string[];
// eslint-disable-next-line @typescript-eslint/no-var-requires
const nodejieba = require("nodejieba");
// 默认使用 nodejieba (C++)
// return nodejieba.tag(hans);
// nodejieba 定义的类型返回值错误,先忽略。
return nodejieba.cutSmall(hans, 4) as unknown as string[];
} catch (ex) {
return [hans];
}
}

0 comments on commit 90886a2

Please sign in to comment.