我有这个文件,但我不知道如何解析这样的文本:
[1]
Word => 'THE'
USED => 53097401461
[2]
Word => 'OF'
USED => 30966074232
然后我必须搜索最常用的单词。 (X为参数)
这是我的 JavaScript:
$.get("https://gist.githubusercontent.com/zach-karat/119d690176f324e3f99c0e312f0a6620/raw/82e14d739e966216536ae9806282a20343e0e2f8/google-books-common-words.txt", function(data, status){
// Thats works once at the time but with letters and not with numbers!
//var hasString = data.includes("HELLO");
var content = data;
$('#content').html(data.replace('\n','<br>'));
});
});
}, 'html');
编辑:
文件上的单词已排序,因此我将代码编辑为:(现在...可以知道长度为 3 个单词的使用中的 TOP10 单词吗?)
$.get("https://gist.githubusercontent.com/zach-karat/119d690176f324e3f99c0e312f0a6620/raw/82e14d739e966216536ae9806282a20343e0e2f8/google-books-common-words.txt", function(data, status,){
var lines = data.split("\n");
var x = 0;
$.each(lines, function(n, elem) {
// append if lenght > 10
$('#content').append('<div>' + elem + '</div>');
x ++;
if(x == 10){//x => parameter
return false;
}
});
});
});
}, 'html');
最佳答案
使用正则表达式分割每一行。
正则表达式:/^([A-Z]+)\s*(\d+)$/gm
说明:
^
- 字符串的开头
([A-Z]+)
- 记住字符 A-Z
的匹配。
\s*
- 1 个或多个空格
(\d+)
- 记住数字 0-9
的匹配。
gm
- 全局
和多行
标志
示例:Regex101
$.get("https://gist.githubusercontent.com/zach-karat/119d690176f324e3f99c0e312f0a6620/raw/82e14d739e966216536ae9806282a20343e0e2f8/google-books-common-words.txt", function(data, status){
var regexp = /^([A-Z]+)\s*(\d+)$/gm;
var html = "";
var content = regexp.exec(data);
while(content)
{
html += "WORD : "+content[1]+"<br>USED : "+content[2]+"<br><br>";
content = regexp.exec(data);
}
$('#content').html(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
关于javascript - 如何使用jQuery搜索txt文件中单词的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51368124/