我正在尝试用c#编写代码,找到一个单词的同义词。
我正在使用Microsoft.Office.Interop.Word.Application
库。
问题是代码给了我太多不相关的单词。它也给了我相反的话
任何人都知道如何改进这个代码或有另一个更好的代码
我正在使用的代码是:
Microsoft.Office.Interop.Word.Application appWord; // word application var
object objNull = null; // word object method calls require
// references to objects... create
// object for null and
object objFalse = false; // false entries and language
object objLanguage = Microsoft.Office.Interop.Word.WdLanguageID.wdEnglishUS; // or appropritate lang!
try
{
// Try opening Word app
appWord = new Microsoft.Office.Interop.Word.Application();
}
catch (System.Exception exc)
{
// could not open word... show error message and return
MessageBox.Show(exc.Message);
return;
}
// clear synonym listbox lbSynonym
lbSynonym.Items.Clear();
// now call get_SynonymInfo to get SynonymInfo structure for
// word entered in TextBox tbWord
Microsoft.Office.Interop.Word.SynonymInfo si =
appWord.get_SynonymInfo(tbWord.Text, ref (objLanguage));
// first find out how many meanings were found for word
int iMeanings = (int)si.MeaningCount;
if (si.MeaningCount > 0)
{
// one or more meanings were found... loop over each
// (notice SynonymInfo.MeaningList is type System.ArrayList!)
var strMeanings = si.MeaningList as Array;
if (strMeanings != null)
foreach (var strMeaning in strMeanings)
{
// get Synonym List for each meaning... note that
// get_SynonymList takes an object ref, thus we
// must create objMeaning object
var objMeaning = strMeaning;
var aSynonyms = si.SynonymList[objMeaning];
var strSynonyms = si.SynonymList[objMeaning] as Array;
if (strSynonyms != null)
foreach (string strSynonym in strSynonyms)
{
// loop over each synonym in ArrayList
// and add to lbSynonym ListBox
lbSynonym.Items.Add(strSynonym);
}
}
}
else
{
// no meanings/synonyms found... set ListBox value to "NONE"
lbSynonym.Items.Add("NONE");
}
答案 0 :(得分:1)
我已将您的代码修改为MCVE,这似乎就是您所做的事情...请告诉我它是否适合您?
void Main()
{
foreach (var value in GetSynonyms("hot"))
{
Debug.WriteLine(value);
}
}
public IEnumerable<string> GetSynonyms(string term)
{
var appWord = new Microsoft.Office.Interop.Word.Application();
object objLanguage = Microsoft.Office.Interop.Word.WdLanguageID.wdEnglishUS;
Microsoft.Office.Interop.Word.SynonymInfo si = appWord.get_SynonymInfo(term, ref (objLanguage));
foreach (var meaning in (si.MeaningList as Array))
{
yield return meaning.ToString();
}
appWord.Quit(); //include this to ensure the related process (winword.exe) is correctly closed.
System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord);
objLanguage = null;
appWord = null;
}
此处更详细的实施:https://gist.github.com/JohnLBevan/c00a02361d4d0a331746995314ad8b58
示例输入和输出:
dictionary
- lexicon
hot
- warm
- sweltering
- spicy
- passionate
actor
- performer
code
- cypher
- program
- system
- cypher
SynonymInfo的相关文档。