使用Microsoft.Office.Interop.Word的字数统计 [英] Word count using Microsoft.Office.Interop.Word
问题描述
如何使用Microsoft.Office.Interop.Word
获取Word文档中特定单词的出现次数?
How can I get the count of occurrences of a particular word in a Word document using Microsoft.Office.Interop.Word
?
例如,在我的Word文档中,我在不同位置有两个##<Test Sub Clause1>##
标记.我需要一个特定文档中它的总数.在我的示例中,该值为2.
For example, in my Word document I have two ##<Test Sub Clause1>##
tags in different places. I need a total count of its occurrence in a particular document. In my example, it will be 2.
Microsoft.Office.Interop.Word
中是否存在任何预定义函数来获取此计数?或最简单的方法是什么?
Is there is any predefined function that exists in Microsoft.Office.Interop.Word
to get this count? Or what is the easiest way to accomplish this?
推荐答案
以下是您可以尝试的方法,它是根据我在 dotnetperls .
Here's something you can try, modified from a code snippet I found at dotnetperls.
using System;
using Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
var wordToFind = "some_word_to_find";
var wordCounter = 0;
// Open a doc file.
var application = new Application();
var document = application.Documents.Open("C:\\word.doc");
// Loop through all words in the document.
for (var i = 1; i <= document.Words.Count; i++)
if (document.Words[i].Text.TrimEnd() == wordToFind)
wordCounter++;
Console.WriteLine("Matches Found: {0}", wordCounter);
// Close word.
application.Quit();
}
}
还有一些文档.
There's also some documentation on MSDN you might want to check out.
这篇关于使用Microsoft.Office.Interop.Word的字数统计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!