我試圖在 C# 中找到一個庫,它可以幫助我進行詞性標記以從句子中識別名詞,但無濟于事。所以我決定根據我下載的文本檔案中的名詞串列檢查字串中的單詞。我的代碼假設句子中的第一個名詞是動詞所指的名詞,我假設這是因為網站上留下的大多數評論都不由很多單詞組成。所以這是我嘗試將文本拆分為一個陣列,然后遍歷 noun.txt 檔案中的每個名詞并查看我的字串是否存在。我的代碼在下面,我只想回傳The first noun found或No noun detected作為我的方法的回傳型別。
string DetectNoun(string param){
//split the input parameter into words based on spaces
string[] words=param.ToLower().Split(" ");
//read all the nouns in the text file into an array:NB all nouns are in lower case
string[] allNouns=File.ReadAllLines("Nouns.txt");
//loop through each noun in the array and check if any exists in our input parameter
int j=0;
for(int i=0;i>allNouns.Length;i ){
if(allNouns[i]==words[j ]){
//return this word as the noun found
return allNouns[i];
}
}
//if no match was found return no noun detected
return "No noun detected";
}
上面用一個樣本輸入測驗了這個Samsung Television, No manual, Box included。No noun was detected盡管電視在我剛剛下載的名詞的文本檔案中,但它仍會不斷回傳。
uj5u.com熱心網友回復:
您的原始代碼有幾個問題:
你是按空格分割的,所以在你的情況下,你會得到(例如)
television,你的單詞串列中有一個逗號。比較時,您是在比較television,television,所以它不匹配。您正在使用
==比較字串進行比較,這在比較字串時會“令人困惑”,您應該使用正確的字串比較器。你的
for回圈被打破了,你只是在比較索引(第一個詞與第一個名詞,第二個詞與第二個名詞等)......此外,如果你的名詞串列小于你的單詞串列,這將引發IndexOutOfRange例外
要解決所有這些問題:
在拆分之前,從字串中洗掉所有不需要的字符。我建議使用正則運算式 (
Regex.Replace(input, @"[^a-zA-Z\d ]", ""),但您需要檢查它是否適合您的輸入(特別是如果接收非 aZ 字母數字字符,如重音或變音符號等)使用 StringComparer.OrdinalIgnoreCase 或 StringComparison.OrdinalIgnoreCase 而不是 go
ToLower()。ToLower()在進行英語以外的文化時,通常不是正確的方法我會使用 Linq 并用它做一個單行:
words.FirstOrDefault(x => allNouns.Contains(x, StringComparer.OrdinalIgnoreCase);
如果 in 中不包含null任何單詞,則回傳,否則為第一個匹配項。wordsallNouns
把它們放在一起:
string DetectNoun(string param){
string[] words = Regex.Replace(param, @"[^a-zA-Z\d ]", "").Split(' ');
// You should cache this somewhere if you plan to call this many times,
// but I'll leave that up to you
string[] allNouns=File.ReadAllLines("Nouns.txt");
return words.FirstOrDefault(x => allNouns.Contains(x, StringComparer.OrdinalIgnoreCase))
?? "No noun detected";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/477484.html
上一篇:展開一維numpy陣列
下一篇:如何比較2支球隊的勝率?在C中
