![](/img/trans.png)
[英]How to use Javascript to read local text file and read line by line?
[英]javascript, how could we read a local text file with accent letters into it?
我有一個疑問,因為我需要讀取一個本地文件並且我一直在研究一些線程,並且我看到了各種處理它的方法,在大多數情況下都有一個輸入文件。
我需要直接通過代碼加載它。
我研究了這個線程:
我可以閱讀它。
令人驚訝的部分是當我嘗試拆分行和單詞時,它顯示: 替換重音字母。
我現在擁有的代碼是:
我的文件閱讀器
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
console.log('The complete text is', allText);
let lineArr = intoLines(allText);
let firstLineWords = intoWords(lineArr[0]);
let secondLineWords = intoWords(lineArr[1]);
console.log('Our first line is: ', lineArr[0]);
let atlas = {};
for (let i = 0; i < firstLineWords.length; i++) {
console.log(`Our ${i} word in the first line is : ${firstLineWords[i]}`);
console.log(`Our ${i} word in the SECOND line is : ${secondLineWords[i]}`);
atlas[firstLineWords[i]] = secondLineWords[i];
}
console.log('The atlas is: ', atlas);
let atlasJson = JSON.stringify(atlas);
console.log('Atlas as json is: ', atlasJson);
download(atlasJson, 'atlasJson.txt', 'text/plain');
}
}
};
rawFile.send(null);
}
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
function intoLines(text) {
// splitting all text data into array "\n" is splitting data from each new line
//and saving each new line as each element*
var lineArr = text.split('\n');
//just to check if it works output lineArr[index] as below
return lineArr;
}
function intoWords(lines) {
var wordsArr = lines.split('" "');
return wordsArr;
}
疑問是:我們如何處理那些帶有重音的元音的特殊字符?
我問這個,因為即使在IDE中,如果我們以UTF-8加載txt,也會出現詢問標記,所以我更改為ISO-8859-1並且加載良好。
我也研究過:
使用 Javascript 從外部文件中讀取 UTF-8 特殊字符
此外,您能否解釋一下是否有更短的方法可以在客戶端 javascript 中加載文件。 例如在 Java 中有 FileReader / FileWriter / BufferedWriter。 在 Javascript 中有類似的東西嗎?
謝謝你的幫助!
聽起來該文件是用 ISO-8859-1(或可能是非常相似的 Windows-1252)編碼的。
這些編碼沒有 BOM 或等效項。
我能看到的唯一解決方案是:
使用(本地)服務器並讓它返回 HTTP Content-Type
標頭,其編碼標識為字符集,例如Content-Type: text/plain; encoding=ISO-8859-1
Content-Type: text/plain; encoding=ISO-8859-1
請改用 UTF-8(例如,在編輯器中以 ISO-8859-1 格式打開文件,然后將其另存為 UTF-8),因為這是 XHR 響應正文的默認編碼。
將您的文本放入具有相應內容類型的.html
文件中,例如:
<meta http-equiv="Content-Type" content="text/html; charset="UTF-8">
將文本括在兩個標簽之間(在我的示例中為“####”)(或放在 div 中)
閱讀html頁面,提取內容並選擇文本:
window.open(url); //.. var content = newWindow.document.body.innerHTML; var strSep="####"; var x = content.indexOf(strSep); x=x+strSep.length; var y = content.lastIndexOf(strSep); var points=content.slice(x, y);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.