[英]Promises/Fetch in JavaScript: how to extract text from text file
[英]how to fetch line from text file in javascript
我正在為 ASR(自動語音識別)開發 web 門戶。 眾所周知,ASR 不會給出 100% 正確的結果。 得到錯誤結果的主要原因是人的說話行為、噪音、說話方式、聲音強度、同音異義詞(購買、再見。引用、站點)等。我計划使用 web 門戶進行后期處理。 我在 textarea 中定義了可以識別的文本。 如果用戶在文本區域中發現錯誤的單詞,那么他將在文本區域中雙擊錯誤的單詞,然后在同一位置選擇單詞后顯示相似的單詞發音選項(相似的發音單詞存儲在文本文件中。一行包含相同的發音單詞)例如。 如果用戶選擇單詞“sad”,那么在選項中他會得到“sad, mad, bad”等。我創建了包含以下行的文本文件
sad, mad, bad
hero, zero
site, cite
buy,bye
如果用戶 select 單詞“site”,那么他將在textarea
中得到“site, cite”,最后用戶將 select 他的正確單詞。 間接地,我在文本文件中搜索單詞,如果在文本文件中找到單詞,則復制整行並在textarea
中顯示為選項(如輸入文本后谷歌顯示的搜索選項)
我編寫了小代碼,但未能完成所有功能。 我的文本文件是本地存儲的。
<textarea name="text" id="textdata" rows="7" cols="79" wrap="soft" maxlength="4000" style="overflow:auto; resize:none; font-size: 17pt; font-family:"Times New Roman"
onselect="populateList(this.value)" > </textarea>
<script>
function populateList(val)
{
// alert("Entered populateList ");
var textComponent = document.getElementById('textdata');
var selectedText;
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
alert("Selected word : "+selectedText);
dic(selectedText);
}
</script>
<script>
$.get("http://localhost/english/master.txt",function(returnedData) {
$("#element").text(returnedData);
},"text/plain");
</script>
<script>
var text = $("#element").text();
var words = text.split(" ");
var dictionary = new Array();
for(var i=0; i < words.length; i++) {
dictionary[i] = words[i];
alert("dictionary elements are :"+dictionary[i]);
}
</script>
<script>
function dic(word) {
alert("Word passed for searching :"+word);
// var dictionary = new Array("Java","Python","Swift","HTML","PHP");
// This line is unnecessary; use the dictionary var already created.
var flag = 0;
for(var i = 0; i < dictionary.length; i++) {
if(dictionary[i] == word) {
document.getElementById("result").innerHTML = "Element Found";
flag = 1;
alert("Element found ");
break;
}
if(i == dictionary.length - 1) {
document.getElementById("result").innerHTML = "Element Not Found";
alert("Element not found ");
}
}
}
</script>
我是網站開發的新手。
我已經解決了你的問題,但我沒有使用 txt 文件,而是使用 json (因為小提琴中的 CORS 問題),但如果你創建 txt 文件,它會工作相同。 文件中一個提示詞的一行。
function populateList(val)
{
let textComponent = document.getElementById('textdata');
let tooltip = document.getElementById('tooltip');
let selectedText;
let startPos = textComponent.selectionStart;
let endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
fetch('https://api.myjson.com/bins/z9wr6').then(data=>data.json()).then(data=>{
let text = data.result.split('\n').reduce((acc,e)=>{
acc.push(Array.prototype.concat.call([],e.split(' ')))
return acc
},[]);
text.forEach(e=>{
if(e.find(ele=>ele===selectedText)){
tooltip.innerHTML = e.join(', ')
}
})
})
}
和工作小提琴: https://jsfiddle.net/bfx8jdgh/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.