gpt4 book ai didi

java - 内存意识字符串过滤

转载 作者:行者123 更新时间:2023-11-30 05:58:06 25 4
gpt4 key购买 nike

假设我有 500 个单词:

Martin
Hopa
Dunam
Golap
Hugnog
Foo
... + 494 more words

我有以下文本,总共约 85KB:

Marting went and got him self stuff from Hopa store and now he is looking to put it into storage with his best friend Dunam. They are planing on using Golap lock that they found in Hugnog shop in Foo town. >... text continues into several pages

我想生成以下文本:

------- went and got him self stuff from ---- store and now he is looking to put it into storage with his best friend ----. They are planing on using ---- lock that they found in ------ shop in --- town. >... text continues into several pages

目前我正在使用commons方法:

String[] 500words = //all 500 words
String[] maskFor500words = // generated mask for each word
String filteredText = StringUtils.replaceEach(textToBeFiltered, 500words , maskFor500words);
  1. 是否有另一种方法可以在内存和 CPU 使用方面更加高效?
  2. 500 个字的最佳存储方式是什么?文件、列表、枚举、数组...?
  3. 如何获得统计数据,例如替换了多少个单词以及哪些单词被替换;以及每个单词被替换了多少次。

最佳答案

我不太关心CPU和内存的使用情况。对于这样的问题和这样的文本量来说,应该是比较小的。我要做的是

  • 有一个包含所有字符串作为键的 Map,以及它们在文本中找到的次数(最初为 0)
  • 使用 StringTokenizer 或 String.split() 方法逐字读取文本
  • 对于每个单词,查找 map 中是否包含该单词(O(1) 操作,非常快)
  • 如果包含它,请将“----”添加到 StringBuilder,并递增为 map 中的单词存储的值
  • 否则添加单词本身(除非它是文本的第一个单词,否则前面有一个空格)

过程结束时,StringBuilder 包含结果,并且映射包含每个单词被用作替换的次数。确保使用原始文本的长度初始化 STringBuilder,以避免过多的重新分配。

应该简单而高效。

关于java - 内存意识字符串过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4761308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com