【问题标题】:How to find the position or location of string in given document如何在给定文档中查找字符串的位置或位置
【发布时间】:2012-12-07 19:31:56
【问题描述】:

如何在给定文档中找到字符串的位置或位置。我有一个 word 文档,我想将它的所有单词和单词位置存储在数据库中,这就是为什么我需要找到单词的位置。

所以请告诉我如何在给定文档中找到单词或字符串的位置或位置。

我打算将 vb.net 或 c# 用于和 .doc 文档

【问题讨论】:

  • 而不是存储所有位置?您是否考虑过动态计算某些单词或文本的位置。似乎浏览一个文档并存储所有单词的位置很乏味
  • 是的......首先我需要能够对每个位置进行微调,然后删除“停用词”并存储我真正需要的位置

标签: c# vb.net ms-word position


【解决方案1】:

嗯...我还没有找到更智能的解决方案 :-/ 但也许这对您有帮助...我们假设您的系统中安装了某些版本的 MS Office。

首先,您必须在项目中添加对名为“Microsoft Word ?* object library”的 Microsoft COM 组件的引用

*?它取决于您的 MS Office 版本

添加参考后,您可以测试此代码:

using System;
using System.Collections.Generic;
using System.Text;
using Word;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {

            // Find the full path of our document

            System.IO.FileInfo ExecutableFileInfo = new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);            
            object docFileName = System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, "document.doc");

            // Create the needed Word.Application and Word.Document objects

            object nullObject = System.Reflection.Missing.Value;
            Word.Application application = new Word.ApplicationClass();
            Word.Document document = application.Documents.Open(ref docFileName, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject, ref nullObject);


            string wholeTextContent = document.Content.Text; 
            wholeTextContent = wholeTextContent.Replace('\r', ' '); // Delete lines between paragraphs
            string[] splittedTextContent = wholeTextContent.Split(' '); // Get the separate words

            int index = 1;
            foreach (string singleWord in splittedTextContent)
            {
                if (singleWord.Trim().Length > 0) // We don´t need to store white spaces
                {
                    Console.WriteLine("Word: " + singleWord + "(position: " + index.ToString() + ")");
                    index++;
                }
            }

            // Dispose Word.Application and Word.Document objects resources

            document.Close(ref nullObject, ref nullObject, ref nullObject);
            application.Quit(ref nullObject, ref nullObject, ref nullObject);
            document = null;
            application = null;

            Console.ReadLine(); 
        }
    }
}

我会测试它,它看起来有效 =)

【讨论】:

  • 非常感谢它的工作原理.....我只是将丢失的 agrument 增加到我的 word COM 版本的 16 cos 并且它需要一些触摸,因为它只显示任何文档的最后一段谢谢所以这么多
  • =) 很高兴它对您有所帮助。问候
  • 在编写这段糟糕的代码时,我想了解更多关于 .NET 的开放式办公库的信息是个好主意...
  • 老板不是一个坏主意....目前我深陷在项目中,再次感谢您的帮助,我添加了停用词删除并能够在数据库中保存我需要的内容 ps。在上面的代码中,我尝试使用 process.start 从 aspx 页面动态更改文件名并从 main() 获取值,但还没有运气。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
相关资源
最近更新 更多