質問は簡単だったのですが、余分な条項が追加されたことは、私にとって大きな頭痛の種であることが判明しました。ここでの問題は、強調表示されたすべての「単語」ではなく、Word ファイルの「フレーズ」が必要なことです。私は次のコードを書きました:
using Word = Microsoft.Office.Interop.Word;
private void button1_Click(object sender, EventArgs e)
{
try
{
Word.ApplicationClass wordObject = new Word.ApplicationClass();
wordObject.Visible = false;
object file = "D:\\mywordfile.docx";
object nullobject = System.Reflection.Missing.Value;
Word.Document thisDoc = wordObject.Documents.Open(ref file, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
List<string> wordHighlights = new List<string>();
//Let myRange be some Range which has my text under consideration
int prevStart = 0;
int prevEnd = 0;
int thisStart = 0;
int thisEnd = 0;
string tempStr = "";
foreach (Word.Range cellWordRange in myRange.Words)
{
if (cellWordRange.HighlightColorIndex.ToString() == "wdNoHighlight")
{
continue;
}
else
{
thisStart = cellWordRange.Start;
thisEnd = cellWordRange.End;
string cellWordText = cellWordRange.Text.Trim();
if (cellWordText.Length >= 1) // valid word length, non-whitespace
{
if (thisStart == prevEnd) // If this word is contiguously highlighted with previous highlighted word
{
tempStr = String.Concat(tempStr, " "+cellWordText); // Concatenate with previous contiguously highlighted word
}
else
{
if (tempStr.Length > 0) // If some string has been concatenated in previous iterations
{
wordHighlights.Add(tempStr);
}
tempStr = "";
tempStr = cellWordText;
}
}
prevStart = thisStart;
prevEnd = thisEnd;
}
}
foreach (string highlightedString in wordHighlights)
{
MessageBox.Show(highlightedString);
}
}
catch (Exception j)
{
MessageBox.Show(j.Message);
}
}
ここで、次のテキストを検討してください。
Le thé vert a un rôle dans la diminution du cholestérol, la 燃焼 des graisses, la prévention du diabète et les AVC, et conjurer la démence.
ここで、誰かが " du cholestérol " を強調表示したとします。私のコードは明らかに " du " と " cholestérol " という 2 つの単語を選択します。連続的に強調表示された領域を 1 つの単語として表示するにはどうすればよいですか? つまり、" du cholestérol " は の 1 つのエンティティとして返される必要がありList
ます。ドキュメントを文字ごとにスキャンし、強調表示の開始点を選択の開始点としてマークし、強調表示の終点を選択の終点としてマークするロジックはありますか?
PS: 他の言語で必要な機能を備えたライブラリがある場合は、シナリオが言語固有ではないため、お知らせください。どういうわけか望ましい結果を得るだけです。
編集: Oliver Hanappi の提案に従ってコードを修正しましたStart
。End
しかし、空白だけで区切られた 2 つのハイライトされたフレーズがある場合、プログラムは両方のフレーズを 1 つと見なすという問題が依然としてあります。単にWords
スペースではなくを読み取るためです。周りに編集が必要かもしれif (thisStart == prevEnd)
ませんか?