【问题标题】:How to detect n phrases or words in a string如何检测字符串中的 n 个短语或单词
【发布时间】:2015-09-12 14:28:58
【问题描述】:

我有一个字符串 s1(包含很多英文句子),一个字符串列表 l1(包含公共汽车、房屋、火车、火车引擎、火车引擎的生命等元素(单词数永远不会大于 3)等)和字符串 l2(类似于 l1)和整数 n 的列表。

对于 l1 的每个元素,我必须在 s 中找到 l1 或 l2 的其他元素(l1 的元素可以在 s 中多次出现,我们必须为每次出现都找到它)使得它们的距离(距离在字数,例如:我有 xyz。在这种情况下,I 和 xyz 之间的距离是 2) 从 l1 的元素到 l1 的元素两侧的 n 小于或等于 n。这些单词/短语(l1 或 l2 的元素)将存储在 java 中的列表中。

e.g.:
Input:
s= i am asd fgh and studying in zxc vbn bnmkl. i am 100 years old.(may contain other symbols too)
l1= i
l2=asd, fgh, zxc, vbn
n=3.

Output:
asd,fgh,zxc,vbn



               for(int j=0;j<l1.size();j++){
                    String s1=l1.get(j);
                    int index = s.indexOf(s1);
                    while(index >= 0) {
                       System.out.println(index);
                       for(int k=0;k<n;){
                           // how to detect the words before and after that element of l1 such that distance is <= n on either side in a passage and they are contained in either l1 or l2.
                       }
                   index = s.indexOf(s1, index+1);
                   }
               }

谁能帮我实现这个?

【问题讨论】:

  • 我们不会为您生成代码。开始编码。回来,当你有一些代码并就你不理解的部分提出具体问题。
  • 你应该看看正则表达式。
  • 我已经添加了代码并添加了我需要帮助的部分(作为评论)。
  • 而不是问“你能帮我实现这个吗?”这只是一种亲切的说法“你能为我做吗?”,我们建议您尝试和试验您的代码并提出一个与疑问直接相关的具体问题。并不是我们没有帮助,而是这样您的问题和他们的回答也会对其他人有所帮助。

标签: java arrays string arraylist


【解决方案1】:

Google 是此类事情的最佳朋友。它也是一个非常简单的函数,可以用不同的方式来解释。

使用循环(for、foreach、while)可能有用,以下链接是这方面的示例。 Find specific word in text file and count it && Count the number of Occurrences of a Word in a String

现在您有了搜索功能,问题是如何设置多个过滤器。


这是一个通用示例

例如如果 s2 变成一个字符串数组

 string[] table = s2.split(' '); // this would do that

然后您可以使用 for 循环来循环遍历每个过滤器,如下所示:

 for (int i = 0; i < table.length(); i++) 
{
  string filter = table[i]; //this would get the filter of the current loop
  // search function here as well as your counters (refer to examples provided)
}

这是另一个例子

  String table_filter = l2.split(" "); //this would split your filter string into an array (at every space) String table_s = s.split(" ");
 //this would split your string into an array (at every space)

 for (int i = 0; i < table_filter.size(); i++){     
 for (int j = 0; j <
 table_s.size(); j++)   
  {     
     // do stuff (like comparing if this = that then do this or using a switch )}

【讨论】:

  • 我意识到在java中,拆分与c#不同,您必须搜索如何将字符串拆分为表格,只需在Google中输入“Java split()”即可有数百个例子
  • 我已经添加了代码并添加了我需要帮助的部分。您的解决方案中的问题是 s 是一个段落,其中可以包含“。”、“”等符号,也可以作为分隔符。
  • 在java中分割字符串:stackoverflow.com/questions/3481828/…
  • 我认为上述方法的问题是如果元素在下一个或下一个数组元素中。这可以检查,但这会使其过于复杂。相反,更好的方法是检查该元素的索引并检测该元素之前和之后的 n 个单词,并检查其中是否包含 l1 或 l2 的元素。但是,我无法在 java 中编写此语句。
猜你喜欢
  • 2015-05-29
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 2019-09-17
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
相关资源
最近更新 更多