识别并提取名词和修饰词

任何想法如何识别和提取名词和修饰符使用VBA(Excel)

例:

带垫片的绿色泵用球阀2in

应该是: 球阀

任何帮助将不胜感激

有一些不同的方法,取决于你期望的句子的types。 在你的例子中,你要提取的两个单词是在句子的开头,并用空格分开。 如果你期望这总是如此,那么你可以使用一些简单的

Function getNoun(ByVal sentence As String) getNoun = "" pos1 = InStr(1, sentence, " ") 'find the first whitespace If pos1 <= 0 Then getNoun = sentence 'if no whitespace, then assume there is only the noun Exit Function End If pos2 = InStr(pos1 + 1, sentence, " ") 'find the second whitespace If pos2 <= 0 Then getNoun = sentence 'if no second whitespace, then assume there is only the noun and qualifier Exit Function End If getNoun = Left(sentence, pos2 - 1) 'if there are two or more spaces, get all chars before the second one End Function 

立即testing:

 ? getNoun("ball valve 2in for green pump with gasket") ball valve ? getNoun("ball valve") ball valve ? getNoun("ball") ball 

如果你的场景更复杂,你需要使用特定的标准来确定哪些单词是所需的名词和限定符,你可能会发现使用正则expression式COM类(请参阅此主题为例)。

编辑:基于评论,我明白,职位是可变的,而且可以接受使用MS Word词库作为参考。 如果代码将在Microsoft Word中运行,以下函数将告诉您一个单词是否是名词:

  Function is_noun(ByVal wrd As String) Dim s As Object, l As Variant is_noun = False Set s = SynonymInfo(wrd) Let l = s.PartOfSpeechList If s.MeaningCount <> 0 Then For i = LBound(l) To UBound(l) If l(i) = wdNoun Then is_noun = True End If Next End If End Function 

如果您没有在MS Word上运行(您的标签build议使用MS Excel),但在目标系统中安装了MS Word,则可以使用上述代码来使用MS Word COM自动化对象。

然后你可以从一个句子中提取第一个名词,下一个单词 – 如果有的话 – 用这样的东西

 Function getNoun(ByVal sentence As String) getNoun = "" Dim wrds() As String wrds = Split(sentence) For i = LBound(wrds) To UBound(wrds) If is_noun(wrds(i)) Then getNoun = wrds(i) If i < UBound(wrds) Then getNoun = getNoun & " " & wrds(i + 1) End If Exit Function End If Next End Function 

但是,请注意,由于这种情况,您在MS Word的数据库中盲目信任,如果您的句子包含可能是动词或名词的单词(取决于上下文),则可能会得到奇怪的结果。 另外,上面的例子将使用MS Word设置的默认语言(可以使用不同的语言 – 如果安装的话 – 通过在SynonymInfo包含语言参数)