首页 > 解决方案 > 在文件中搜索字符串数组

问题描述

我有一个文本文件,testFile.txt还有一个要在文件中搜索的字符串数组,比如['year', 'weather', 'USD 34235.00', 'sportsman', 'ಕನ್ನಡ']. 我可以使用NodeJS 自然将文件分解为标记,也许可以从中创建一个数组(〜字符串数组中条目数的 100-200 倍)。然后,对两个数组进行排序并开始搜索。或者,lodash直接使用?

Found结果是在文本文件中找到搜索字符串数组中的至少一个字符串;否则,它应该被视为NotFound

实施此类搜索有哪些选项?

标签: node.jsarraysnlpfull-text-searchstringtokenizer

解决方案


我可以建议使用Set大量标记,然后遍历搜索词数组,检查标记是否设置has了这些词之一。如果 terms 数组也很大,您可以考虑使用SetMDN 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))


推荐阅读