count_words
Measure word count in text files for English or Japanese. Specify the file path in Windows or WSL/Linux format. Uses morphological analysis for Japanese and space separation for English.
Instructions
ファイルの単語数を計測します。絶対パスを指定してください(Windows形式 C:\Users...、またはWSL/Linux形式 /c/Users/... のどちらも可)。英語ではスペースで区切られた単語をカウントし、日本語では形態素解析を使用します。
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes | 単語数をカウントするファイルのパス(Windows形式かWSL/Linux形式の絶対パスを推奨) | |
| language | No | ファイルの言語 (en: 英語, ja: 日本語) | en |
Implementation Reference
- src/index.ts:204-265 (handler)Core handler implementation for counting words in text. Handles English (space-separated) and Japanese (using kuromoji tokenizer for morphemes, excluding symbols and spaces). Returns formatted result or error.private async countTextWordsImpl(text: string, language: 'en' | 'ja' = 'en', sourceName: string = 'テキスト') { try { let wordCount = 0; let resultText = ''; if (language === 'en') { // 英語の場合、単語はスペースで区切られているためsplitで分割 const words = text.trim().split(/\s+/); wordCount = words.length; resultText = `${sourceName}の単語数: ${wordCount}単語 (英語モード)`; } else if (language === 'ja') { // 日本語の場合、kuromojiを使用して形態素解析 // 形態素解析器が利用可能かを確認 let tokenizer; try { tokenizer = await initializeTokenizer(); } catch (error) { return { content: [{ type: 'text' as const, text: '形態素解析器の初期化に失敗しました。しばらく待ってから再試行してください。' }], isError: true }; } // 形態素解析を実行 const tokens = tokenizer.tokenize(text); // 記号と空白以外のすべての単語をカウント(助詞や助動詞も含める) const meaningfulTokens = tokens.filter((token: any) => { // 記号と空白のみを除外 return !(token.pos === '記号' || token.pos === '空白'); }); wordCount = meaningfulTokens.length; // 単語の詳細情報を出力 const tokenDetails = tokens.map((token: any) => { return `【${token.surface_form}】 品詞: ${token.pos}, 品詞細分類: ${token.pos_detail_1}, 読み: ${token.reading}`; }).join('\n'); resultText = `${sourceName}の単語数: ${wordCount}単語 (日本語モード、すべての品詞を含む)\n\n分析結果:\n${tokenDetails}\n\n有効な単語としてカウントしたもの:\n${meaningfulTokens.map((t: any) => t.surface_form).join(', ')}`; } return { content: [{ type: 'text' as const, text: resultText }] }; } catch (error: any) { return { content: [{ type: 'text' as const, text: `エラーが発生しました: ${error.message}` }], isError: true }; } }
- src/index.ts:498-501 (schema)Zod schema defining input parameters for the count_words tool: filePath (string) and optional language (en|ja, default en).{ filePath: z.string().describe('単語数をカウントするファイルのパス(Windows形式かWSL/Linux形式の絶対パスを推奨)'), language: z.enum(['en', 'ja']).default('en').describe('ファイルの言語 (en: 英語, ja: 日本語)') },
- src/index.ts:495-518 (registration)MCP tool registration for 'count_words': specifies name, Japanese description, Zod schema, and inline async handler that resolves file path, reads content, and delegates to countTextWordsImpl.this.server.tool( 'count_words', 'ファイルの単語数を計測します。絶対パスを指定してください(Windows形式 C:\\Users\\...、またはWSL/Linux形式 /c/Users/... のどちらも可)。英語ではスペースで区切られた単語をカウントし、日本語では形態素解析を使用します。', { filePath: z.string().describe('単語数をカウントするファイルのパス(Windows形式かWSL/Linux形式の絶対パスを推奨)'), language: z.enum(['en', 'ja']).default('en').describe('ファイルの言語 (en: 英語, ja: 日本語)') }, async ({ filePath, language }) => { try { // ファイルパスを解決 const resolvedPath = resolveFilePath(filePath); const fileContent = fs.readFileSync(resolvedPath, 'utf8'); return await this.countTextWordsImpl(fileContent, language, `ファイル '${resolvedPath}'`); } catch (error: any) { return { content: [{ type: 'text' as const, text: `ファイル読み込みエラー: ${error.message}` }], isError: true }; } } );
- src/index.ts:125-149 (helper)Helper function to resolve file paths, handling absolute paths, WSL to Windows conversion, and relative paths.function resolveFilePath(filePath: string): string { try { // WSL/Linux形式のパス (/c/Users/...) をWindows形式 (C:\Users\...) に変換 if (filePath.match(/^\/[a-zA-Z]\//)) { // /c/Users/... 形式を C:\Users\... 形式に変換 const drive = filePath.charAt(1).toUpperCase(); let windowsPath = `${drive}:${filePath.substring(2).replace(/\//g, '\\')}`; console.error(`WSL/Linux形式のパスをWindows形式に変換: ${filePath} -> ${windowsPath}`); if (fs.existsSync(windowsPath)) { console.error(`変換されたパスでファイルを発見: ${windowsPath}`); return windowsPath; } } // 通常の絶対パスの処理 if (path.isAbsolute(filePath)) { if (fs.existsSync(filePath)) { console.error(`絶対パスでファイルを発見: ${filePath}`); return filePath; } // 絶対パスでファイルが見つからない場合はエラー throw new Error(`指定された絶対パス "${filePath}" が存在しません。パスが正しいか確認してください。` +