【问题标题】:How to remove a particular word from a text that satisfies a condition? [closed]如何从满足条件的文本中删除特定单词? [关闭]
【发布时间】:2015-02-11 18:50:10
【问题描述】:

我有一个包含很多单词的文本文件。我想删除包含重复字母的单词(例如 zoos - 包含 2 个 o's)。最好的方法是什么?

【问题讨论】:

  • 你能展示你到目前为止所做的工作吗?

标签: java regex algorithm input file-handling


【解决方案1】:

Regular expressions 可能适合您。类似的东西

Pattern p = Pattern.compile("([a-zA-Z])*([a-zA-Z])\\2([a-zA-Z])*");
Matcher m = p.matcher("zoo");
System.out.println(m.matches());

只需添加一个循环来尝试文件中的每个单词,如果 m.matches() == true - 删除它。

顺便说一句,如果你输入喜欢这个,这将不起作用

【讨论】:

  • 将 [Oo] 更改为 [a-zA-Z]。他说重复的字符不是重复的。
  • 感谢指正
  • 没问题的小家伙。为您的努力 +1 :)
  • 那不匹配 'ab' 和其他至少有两个字母的单词吗?
  • 实际上,你想要的是 /([[:alpha:]])\1/ - [[:alpha:]] 匹配任何字母字符, (...) 使它捕获组,\1 是对该捕获组的反向引用,因此它匹配任何重复的字母字符。
【解决方案2】:

这是一个使用正则表达式和流 api 的示例:

package demo;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Demonstration
{
    public static void main(String[] args)
    {
        List<String> input = Arrays.asList( //
            new String[] {"a", "bb", "ccc", "ded", "ff", "ghi", "jkll"});

        // Prints [a, ded, ghi]
        System.out.println(removeWordsWithRepetitiveCharacters(input));
    }

    private static List<String> removeWordsWithRepetitiveCharacters(List<String> words)
    {
        return words.stream() //
            .filter(word -> !word.matches(".*(\\w)\\1+.*")) //
            .collect(Collectors.toList());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 2022-10-24
    • 2013-03-23
    相关资源
    最近更新 更多