.net将Word,Pdf等文档文件中的文本提取出来代码分享

Java 版本
【菜科解读】
经常有人问我怎么将类似word,pdf这样的文档转换为文本然后索引,.net 这方面的解决方案不是很多,为了方便大家,我花了一天时间自己做了一个。
Java 版本的 lucence 提供了一个 tika 的工具用于将 word, excel, pdf 等文档转换为文本,然后进行索引。
但这个工具没有 .net 版本,要在 .net 下用,需要用 IKVM.net,很麻烦。
而且这个工具实际上底层是调用 POI 和 PDFParse 来转换的。
从网上搜索到的信息看,POI 对 office 2007 以上版本的文档处理有问题,不知道最新版本是否解决了,我没有试过。
PDFParse 这个东西,我用过 .net 版本,对中文不支持,不知道 Java 版本是否支持。
其实 .net 下完全不需要用这些开源解决方案来解决,因为微软提供了一个官方的解决方案,这个解决方案叫 IFilter,这个过滤器是为 sql server 的全文索引设计的,但第三方软件可以调用API来完成文档的提取工作。
为了方便大家,我把 IFilter 转换的功能封装到了一个开源的组件中去,大家可以到下面地址去下载源码:HBTextParse.
调用很简单:
这个是提取文件中的文本到字符串的代码
if (openFileDialog.ShowDialog() == DialogResult.OK) //要转换的文件 textBoxFilePath.Text = openFileDialog.FileName; //实例化 TextParse ,传入要转换的文件路径 TextParse textParse = new TextParse(textBoxFilePath.Text); //提取文件中的文本,并输出 richTextBoxView.Text = textParse.ConvertToString();}这个是将文件转换为文本文件的代码:
if (saveFileDialog.ShowDialog() == DialogResult.OK) //实例化 TextParse,传入要转换的文件的路径 TextParse textParse = new TextParse(textBoxFilePath.Text); //将文件转换到 saveFileDialog.FileName 指定的文本文件中 textParse.ConvertToFile(saveFileDialog.FileName); catch (Exception ex) MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);}
要注意的问题是提取 Pdf 文档,如果机器是 64为操作系统,必须要安装Adobe PDF iFilter 9 for 64-bit platforms. 否则会报异常。
这个问题我搞了将近一天才搞定。
支持的文档类型:
目前这个组件可以支持所有 Microsoft office 提供的文档类型,包括 *.rtf, *.doc, *.docx, *.xls, *.xlsx, *.ppt, *.pptx 等等
除了微软Office的文档外,还可以转换
html 文档:可以把html文档中的文本提取出来(不包含标签)
Pdf 文档:我测试过,对中文支持没有问题
Txt 文档
这个代码的核心部分是一个叫 FilterCode 的类。
这个类是从http://ifilter.codeplex.com/这个地方下载的,我对这个类做了改进,加入了转换到文件的方法。
我把这个类的代码贴出来,如果对如何调用IFilter的windows API感兴趣,可以参考这段代码
IFilter 的相关API函数如下:通常这些API函数就可以通过IFilter接口提取文本。
[DllImport("query.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern int LoadIFilter(string pwcsPath, [MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, ref IFilter ppIUnk);
[ComImport, Guid("89BCB740-6119-101A-BCB7-00DD010655AF")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IFilter /// /// The IFilter::Init method initializes a filtering session. /// [PreserveSig] IFilterReturnCodes Init( //[in] Flag settings from the IFILTER_INIT enumeration for // controlling text standardization, property output, embedding // scope, and IFilter access patterns. IFILTER_INIT grfFlags, // [in] The size of the attributes array. When nonzero, cAttributes // takes // precedence over attributes specified in grfFlags. If no // attribute flags // are specified and cAttributes is zero, the default is given by // the // PSGUID_STORAGE storage property set, which contains the date and // time // of the last write to the file, size, and so on; and by the // PID_STG_CONTENTS // 'contents' property, which maps to the main contents of the // file. // For more information about properties and property sets, see // Property Sets. int cAttributes, //[in] Array of pointers to FULLPROPSPEC structures for the // requested properties. // When cAttributes is nonzero, only the properties in aAttributes // are returned. IntPtr aAttributes, // [out] Information about additional properties available to the // caller; from the IFILTER_FLAGS enumeration. out IFILTER_FLAGS pdwFlags); /// /// The IFilter::GetChunk method positions the filter at the beginning /// of the next chunk, /// or at the first chunk if this is the first call to the GetChunk /// method, and returns a description of the current chunk. /// [PreserveSig] IFilterReturnCodes GetChunk(out STAT_CHUNK pStat); /// /// The IFilter::GetText method retrieves text (text-type properties) /// from the current chunk, /// which must have a CHUNKSTATE enumeration value of CHUNK_TEXT. /// [PreserveSig] IFilterReturnCodes GetText( // [in/out] On entry, the size of awcBuffer array in wide/Unicode // characters. On exit, the number of Unicode characters written to // awcBuffer. // Note that this value is not the number of bytes in the buffer. ref int pcwcBuffer, // Text retrieved from the current chunk. Do not terminate the // buffer with a character. [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder awcBuffer); /// /// The IFilter::GetValue method retrieves a value (public /// value-type property) from a chunk, /// which must have a CHUNKSTATE enumeration value of CHUNK_VALUE. /// [PreserveSig] IFilterReturnCodes GetValue( // Allocate the PROPVARIANT structure with CoTaskMemAlloc. Some // PROPVARIANT // structures contain pointers, which can be freed by calling the // PropVariantClear function. // It is up to the caller of the GetValue method to call the // PropVariantClear method. // ref IntPtr ppPropValue // [MarshalAs(UnmanagedType.Struct)] ref IntPtr PropVal); /// /// The IFilter::BindRegion method retrieves an interface representing /// the specified portion of the object. /// Currently reserved for future use. /// [PreserveSig] IFilterReturnCodes BindRegion(ref FILTERREGION origPos, ref Guid riid, ref object ppunk); }
从文档中提取文本的代码如下:
/// /// Utilizes IFilter interface in Windows to parse the contents of files. /// ///
Path - Location of file to parse ///
Buffer - Return text artifacts /// Raw set of strings from the document in plain text format. public void GetTextFromDocument(string path, ref StringBuilder buffer) IFilter filter = null; int hresult; IFilterReturnCodes rtn; // Initialize the return buffer to 64K. buffer = new StringBuilder(64 * 1024); // Try to load the filter for the path given. hresult = LoadIFilter(path, new IntPtr(0), ref filter); if (hresult == 0) IFILTER_FLAGS uflags; // Init the filter provider. rtn = filter.Init( IFILTER_INIT.IFILTER_INIT_CANON_PARAGRAPHS | IFILTER_INIT.IFILTER_INIT_CANON_HYPHENS | IFILTER_INIT.IFILTER_INIT_CANON_SPACES | IFILTER_INIT.IFILTER_INIT_APPLY_INDEX_ATTRIBUTES | IFILTER_INIT.IFILTER_INIT_INDEXING_ONLY, 0, new IntPtr(0), out uflags); if (rtn == IFilterReturnCodes.S_OK) STAT_CHUNK statChunk; // Outer loop will read chunks from the document at a time. For those // chunks that have text, the contents will be pulled and put into the // return buffer. bool bMoreChunks = true; while (bMoreChunks) rtn = filter.GetChunk(out statChunk); if (rtn == IFilterReturnCodes.S_OK) // Ignore all non-text chunks. if (statChunk.flags != CHUNKSTATE.CHUNK_TEXT) continue; // Check for white space items and add the appropriate breaks. switch (statChunk.breakType) case CHUNK_BREAKTYPE.CHUNK_NO_BREAK: break; case CHUNK_BREAKTYPE.CHUNK_EOW: buffer.Append(' '); break; case CHUNK_BREAKTYPE.CHUNK_EOC: case CHUNK_BREAKTYPE.CHUNK_EOP: case CHUNK_BREAKTYPE.CHUNK_EOS: buffer.AppendLine(); break; // At this point we have a text chunk. The following code will pull out // all of it and add it to the buffer. bool bMoreText = true; while (bMoreText) // Create a temporary string buffer we can use for the parsing algorithm. int cBuffer = DefaultBufferSize; StringBuilder sbBuffer = new StringBuilder(DefaultBufferSize); // Read the next piece of data up to the size of our local buffer. rtn = filter.GetText(ref cBuffer, sbBuffer); if (rtn == IFilterReturnCodes.S_OK || rtn == IFilterReturnCodes.FILTER_S_LAST_TEXT) // If any data was returned, scrub it and then add it to the buffer. CleanUpCharacters(cBuffer, sbBuffer); buffer.Append(sbBuffer.ToString()); // If we got back some text but there is no more, terminate the loop. if (rtn == IFilterReturnCodes.FILTER_S_LAST_TEXT) bMoreText = false; break; // Once all data is exhausted, we are done so terminate. else if (rtn == IFilterReturnCodes.FILTER_E_NO_MORE_TEXT) bMoreText = false; break; // Check for any fatal errors. It is a bug if you land here. else if (rtn == IFilterReturnCodes.FILTER_E_NO_TEXT) System.Diagnostics.Debug.Assert(false, "Should not get here"); throw new InvalidOperationException(); // Once all chunks have been read, we are done with the file. else if (rtn == IFilterReturnCodes.FILTER_E_END_OF_CHUNKS) bMoreChunks = false; break; else if (rtn == IFilterReturnCodes.FILTER_E_EMBEDDING_UNAVAILABLE || rtn == IFilterReturnCodes.FILTER_E_LINK_UNAVAILABLE) continue; else throw new COMException("IFilter COM error: " + rtn.ToString()); else // If you get here there is no filter for the file type you asked for. Throw an // exception for the caller. throw new InvalidOperationException("Failed to find IFilter for file " + path); }
.net,将,Word,Pdf,等,文档,文件,中的,文本,世界三大未解谜团,两件在中国,最终一个若破解将颠覆人类文明!
彭加木失踪谜团新疆新疆罗布泊自古以来就被成为“死亡之海”,又因地形酷似一只耳朵,也叫“地球之耳”,在几千年的古代上,新疆新疆罗布泊据流传各种神奇传说,其中最为出名的就是楼兰古国,而彭加木失踪一事更是让新疆新疆罗布泊变得更加神奇。
彭加木并非首次考察新疆新疆罗布泊,1964年,他就在新疆新疆罗布泊采集水样和矿物,1979年,他跟日本专家合作,再次来到新疆新疆罗布泊考察,历经1月,他们重走了楼兰环绕新疆新疆罗布泊达到羌的丝绸之路中段。
然而第三次1980年5月再次深入新疆新疆罗布泊时,却因为独自寻找水源失踪了,虽然派出了搜救部队,搜救人员更达到了1029人,前后寻找了41天,寻找面积为1011平方公里,先后四次地毯式搜寻,但依旧没有找到彭加木,那么彭加木到底去那里。
陆地的“百慕大三角”百慕大是指百慕大群岛、美国的迈阿密和波多黎各的圣胡安三点连线形成的一个大西洋三角地带,这里也上演着各种各样失踪事件,甚至还有传出过百慕大“时空穿越”的说法,各种奇妙的事件的发生,也是让人将百慕大称为“魔鬼三角洲”。
无独有偶,除了“魔鬼三角洲”之外,在我国四川还有一个瓦屋山迷魂凼,其经纬度在2932— 2934之间,这个纬度又刚好与耸人听闻的百慕大三角相似,不仅如此,迷魂凼同样也有各种奇妙的事件。
一旦进入迷魂凼,手机、GPS、指南针全都会失灵,从1970年开始,就有人迷失在迷魂凼当中,1975年洪雅当地组织的野生动物调查小组,就试图解开迷魂凼谜团,但刚刚进入迷魂凼就迷失了方向,他们不得不原路返回。
几十年来,林业厅、动物保护组织、世界动物基金会都派出了考察队,可都无功而返,科考队曾在迷魂凼释放信鸽,想让它飞出去,结果鸽子在上空盘旋了一圈,又落回队员肩膀上,根本不敢飞走。
而且迷魂凼常年都充斥着的浓雾,为了防止有人在这里面迷失,当地管委会就将迷魂凼列为了禁地,禁止游客进入,据说迷魂凼是五斗米教的创始人张陵修道的地方,他在这里还设下了迷魂阵。
人类的起源“物竞天择,适者生存”,达尔文的进化理论解释了人类的起源问题,他认为人类是由南方古猿进化而来,但从古猿进化到人类,找不到太多的共同点,在史前进化时期,似乎存在着一段空白期,人类就好像凭空出现了一样。
加上近年来,史前人类的活动痕迹不断被发现,而人体的潜能又非常神奇,比如人又为何会自燃,人体自燃现象早17世纪就已经出现了,300多年来,科学界一直都试图给出一个合理的解释,但至今没有找到任何答案侦破纪实:若是破解人类这一秘密,人类文明或许会重新洗牌。
更多请关注幼师蕊蕊!
人在死亡即将来临前的?10?个迹象
这个词很敏感,很容易让人产生紧张感,然而死亡却是再正常不过的一种生理表现,所有的人类都需要面对它。
因为没有人可以长生不死。
科学家在经过长期的实践研究后,总结了人在死亡即将来临前的19个迹象。
我们一起来看看吧!1)食欲下降。
在死亡前的身体不再需要像健康时的那么多能量。
因此,一个人对食物或喝的东西要少得多,而且几乎不会感到饥饿。
在死亡前几天,他可能会完全拒绝进食和喝水。
2)表现的十分嗜睡。
一个人在死亡前 2-3 个月开始保持清醒的频率减少。
很容易就睡着了,坐着或者躺着。
这是由于人体新陈代谢减慢,代谢能量缺乏所致。
3)没有力气与人沟通。
他在死亡前不愿意与人讲话或者沟通,是因为没有了精力。
也许是不希望别人看见自己的虚弱表现。
4)生命体征发生变化。
当一个人接近死亡时,他的血压会下降,呼吸会变得不均匀,心跳会变得不规则。
尿液变色——由于肾功能衰竭,尿液可能会变成棕色。
5)身体会不听使唤。
起初是无法站起来,然后来拿翻身都困难了。
最后,可能连杯子都拿不住了——因为手脚会不听使唤。
6体温降低。
人死亡前几天,血液循环会减少。
血液集中在内脏器官中,很少流向手臂和腿部。
皮肤会感觉冰冷,很可能苍白,并带有蓝色或紫色斑点。
7)思绪混乱。
大脑一般是最后死亡的,一个人即使快要死了,也会听到别人对他的称呼。
他甚至可能尝试回应,但他的思绪会变得混乱,他的言语也会变得不连贯8)呼吸变化明显。
死亡前可能开始呼吸更慢、喘气、呼吸长时间停顿。
9)身体的疼痛加剧。
尤其是癌症患者,这种情况经常发生。
剧烈的疼痛感让人难以忍受。
10)出现幻觉。
他仿佛又回到了童年,与死去已久的亲人在一起。
也许会呼唤曾经的朋友的名字。
感觉看见某个人,并不时与之对话。