node.js - 在文件中搜索字符串数组
问题描述
我有一个文本文件,testFile.txt
还有一个要在文件中搜索的字符串数组,比如['year', 'weather', 'USD 34235.00', 'sportsman', 'ಕನ್ನಡ']
. 我可以使用NodeJS 自然将文件分解为标记,也许可以从中创建一个大数组(〜字符串数组中条目数的 100-200 倍)。然后,对两个数组进行排序并开始搜索。或者,lodash
直接使用?
Found
结果是在文本文件中找到搜索字符串数组中的至少一个字符串;否则,它应该被视为NotFound
。
实施此类搜索有哪些选项?
解决方案
我可以建议使用Set
大量标记,然后遍历搜索词数组,检查标记是否设置has
了这些词之一。如果 terms 数组也很大,您可以考虑使用Set
(MDN docs for Set)
您可以从此评论中看到在大量元素的上下文中数组和集合之间的性能比较
下面是演示片段
const tokens1 = ['ಕನ್ನಡ', 'asdasd', 'zxczxc', 'sadasd', 'wqeqweqwe', 'xzczxc']
const tokens2 = ['xzczcxz', 'asdqwdaxcxzc', 'asdxzcxzc', 'wqeqwe', 'zxczcxzxcasd']
const terms = ['year', 'weather', 'USD 34235.00', 'sportsman', 'ಕನ್ನಡ']
const set1 = new Set(tokens1)
const set2 = new Set(tokens2)
const find = (tokensSet, termsArray) => {
for (const term of termsArray) {
if (tokensSet.has(term)) {
return 'Found'
}
}
return 'Not Found'
}
console.log(find(set1, terms))
console.log(find(set2, terms))
推荐阅读
- mysql - 更改 MySQL 设置文件中数据库信息参数的命令是什么?在bash?
- node.js - Heroku 部署后找不到猫鼬模块?
- node.js - 如何在 Deno 中不使用换行符来 console.log?
- ruby-on-rails - Rails 在一个模型条目上验证两个不同的正则表达式
- java - @ResponseBody 和 @PostMapping 之间的冗余(路径 =“/test”,消耗 =...,产生 = MediaType.APPLICATION_JSON_VALUE)?
- sql - 将两个查询合并为一个查询
- android - 无法解析外部依赖项 com.android.tools.build:gradle:4.0.1,因为没有定义存储库
- python - 使 tkinter 网格交错
- python - 需要一些帮助将程序更改为面向对象的程序
- amazon-web-services - 什么是云形成 SSHLocation 语法?