3

我正在用 Java 编写这个程序来查找文本文件中的唯一单词。我想知道这段代码是否正确,因为它甚至将空格显示为单词。

String[] words;
List<String> uniqueWords = new ArrayList<String>();
words = str1.split("[!-~]* ");
for (int i = 0; i < words.length; i++)
{
    if (!(uniqueWords.contains (words[i])))
    {
        uniqueWords.add(words[i]);
    }
}

例如,如果我的输入是“Hello world!世界怎么样?” 我的输出数组/集合/列表应该有 hello, world, how, is, the

4

6 回答 6

5

您可以使用Set找到唯一的单词。Set 是一个不包含重复元素的集合。

String[] words;
Set<String> uniqueWords = new HashSet<String>();
words = str1.split("[\\W]+");
for (int i = 0; i < words.length; i++)
{
    uniqueWords.add(words[i]);
}
于 2013-03-20T11:32:26.277 回答
4

其他答案的略微修改版本(我喜欢它简短而简单):

String[] words = str1.split("[!-~]* ");
Set<String> uniqueWords = new HashSet<String>();

for (String word : words) {
    uniqueWords.add(word);
}

注意:如果你想在!-~或空间上分割,你应该使用这个:

String[] words = str1.split("[-!~\\s]+");

(破折号必须是第一个或最后一个)

于 2013-03-20T11:40:28.850 回答
2

如果我们真的要紧凑:

Set<String> unique = new HashSet<String>(Arrays.asList(str.toLowerCase().split("[-.,:;?!~\\s]+")));
于 2013-03-20T11:50:06.677 回答
1

Set 不允许重复,而 List 允许重复。

String[] words;
Set<String> uniqueWords = new HashSet<String>();
words = str1.split("[!-~]* ");
for (int i = 0; i < words.length; i++)
    uniqueWords.add(words[i]); //Here you need not to check with set because it wont allow duplicates
于 2013-03-20T11:33:54.823 回答
0

我建议您使用模式和匹配器并将结果放入 Set 中。

public void getWords()
{
    Set<String> words = new HashSet<String>();
    String pattern = "[a-zA-Z]+\\s";
    String match = "hello world how* are. you! world hello";
    Pattern compile = Pattern.compile(pattern);
    Matcher matcher = compile.matcher(match);
    while(matcher.find())
    {
        String group = matcher.group();
        boolean add = words.add(group);
        if(add)
        {
            System.out.println(group);
        }
    }
}

输出:

hello 
world 

通过改变模式来改变你对“词”的定义。

于 2013-03-20T11:40:57.063 回答
0

如果您想获取句子/任何文本中未重复的单词,您可以尝试以下操作:

   public static Map<String,Integer> getUniqueWords(String sentence){
   String[] word = sentence.split("[\\W]+");
        Map<String,Integer> uniqueWord = new HashMap<>();
        for (String e:word){
            if(!uniqueWord.containsKey(e)){
                uniqueWord.put(e,1);
            }else{
                uniqueWord.remove(e);
            }
        }
        return uniqueWord;
    }
于 2017-07-25T03:42:49.343 回答