【问题标题】:How can I measure the distance between two words in Java? [closed]如何测量Java中两个单词之间的距离? [关闭]
【发布时间】:2013-11-20 10:17:05
【问题描述】:

非常简单的问题:如何在 Java 中测量文本中两个单词之间的距离?例如,文本可以是:

汽车的颜色蓝色

这句话中colorblue这个词的距离怎么算?我知道从 colorblue 的距离是 5。在 Java 中我怎样才能得到这个 5 的距离?

提前致谢。

【问题讨论】:

  • 你凭什么说颜色和蓝色之间的距离是5?它是 4 或 15。不过,您尝试过的代码在哪里,什么似乎不起作用?
  • 不,距离是5,但是他问的方式很奇怪
  • 你之前可以做一些研究 - 可能与 How to compare almost similar Strings in Java? (String distance measure) 重复
  • 用空格分割句子并使用索引找出所谓的距离。
  • @Fabinout 我问的方式并不奇怪。我只是在询问语料库中两个单词实体之间的距离。这有什么奇怪的?你说它很奇怪会让你很奇怪。

标签: java


【解决方案1】:

你可以这样做:

  1. Split 根据空格排列的数组。
  2. 获取第一个单词的索引
  3. 获取第二个单词的索引。
  4. 减去索引,就是“距离”。

把它翻译成 Java 很简单。我把它留给你。

【讨论】:

    【解决方案2】:

    这可能是解决方案的近似值:

    public static void main(String[] args) {
        final String strWords = "The color of the car is blue.";
        final String word1 = "color";
        final String word2 = "blue";
    
        // Remove any special chars from string
        final String strOnlyWords = strWords.replace(",", "").replace(".", "");
    
        final List<String> words = Arrays.asList(strOnlyWords.split(" "));
        final int index1 = words.indexOf(word1);
        final int index2 = words.indexOf(word2);
        int distance = -1;
    
        // Check index of two words
        if (index1 != -1 && index2 != - 1) {
            distance = index2 - index1;
        }
    
        System.out.println(distance);
    }
    

    【讨论】:

    • 太棒了。非常感谢。
    【解决方案3】:

    你可以通过以下代码来实现:

        String s = "The color of the car is blue";
        String[] arr = s.split(" ");
        int startIndex = -1;
        int endIndex = -1;
        for(int i=0; i<arr.length; i++){
            if(arr[i].equals("color")){
                startIndex = i;
            }
            else if(arr[i].equals("blue")){
                endIndex = i;
            }
        }
        System.out.println("distance is: " + (endIndex-startIndex));
    

    【讨论】:

    • 这里不鼓励用勺子向 OP 提供答案(特别是在没有显示任何努力的情况下)。
    • @R.J 他正在给 OP 一个具体而具体的答案。 OP 如果他们想将它用于任何事情(提示,他们的作业)将不得不对其进行概括,将其包装在一个方法中,并可能对其进行优化(给定的答案是 O(n) 但你可以让它成为 O(1 ) 如果不计算预处理)。
    • @John - 将此代码放入方法中有多难?啊,现在在一个方法中查看下面的另一个答案。这就是为什么在 OP 完全没有表现出任何努力的情况下不鼓励这种做法的原因。
    • @R.J 我认为代码示例对新手用户有帮助
    • @Meet - 相信我。这一次可能会对他们有所帮助,但后来,他们会遇到很多困难。而且只会鼓励他们提出更多这样的问题,这对 OP 或社区都不利。
    猜你喜欢
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2013-04-28
    • 2011-07-10
    相关资源
    最近更新 更多