标签唯一性

时间:2013-10-07 00:37:49

标签: java arraylist hashtag

我试图从用户输入的推文中找到唯一的主题标签。我哥哥在帮助我,但他不得不离开。无论如何,所以我有代码来查找输入中使用单词的次数,但我只需要知道使用的不同主题标签的数量。例如,在输入“#one #two blue red #one #green four”中,将有3个唯一的主题标签为#one,#two和#green。我无法弄清楚如何编码。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Tweet {


public static void main(String[] args) {
Scanner hashtag = new Scanner( System.in );
System.out.println( "Please enter a line of text" );
String userInput = hashtag.nextLine();

userInput = userInput.toLowerCase();

userInput = userInput.replaceAll( "\\W", " " );     // strip out any non words.
userInput = userInput.replaceAll( "  ", " " );      // strip out any double spaces
                                                    //   created from stripping out non words
                                                    //   in the first place!
String[] tokens = userInput.split( " " );
System.out.println( userInput );

ArrayList< String > tweet = new ArrayList< String >();

tweet.addAll( Arrays.asList( tokens ) );

int count = 0;

for( int i = 0; i < tweet.size(); i++ )
{
    System.out.printf( "%s: ", tweet.get( i ) );
    for( int j = 0; j < tweet.size(); j++ )
    {
        if( tweet.get( i ).equals( tweet.get( j ) ) )
            count++;
        if( tweet.get( i ).equals( tweet.get( j ) ) && count > 1 )
            tweet.remove( j );                      // after having counted at least
    }                                               // one, remove duplicates from List        
    System.out.printf( "%d\n", count );
    count = 0;
}

} }

2 个答案:

答案 0 :(得分:2)

这是您可以使用的一些工作代码。

我删除了你的字符串替换,因为我不确定你为什么要删除非单词字符 - 你要删除主题标签上的'#'。多个空格不是问题 - split()只会把它们变成无害的空字符串。

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class HashTags {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter a line of text");
        String tweet = scanner.nextLine();
        Set<String> hashtags = getHashtags(tweet);      
        System.out.println(hashtags.toString());
    }

    public static Set<String> getHashtags(String tweet) {
        String[] words = tweet.split(" ");
        Set<String> hashtags = new HashSet<String>();
        for (String word : words) {
            if (word.startsWith("#")) {
                hashtags.add(word);
            }
        }
        return hashtags;
    }
}

以下是样本运行的输出:

Please enter a line of text
#one #two blue red #one #green four     #jaja hg
[#one, #two, #jaja, #green]

答案 1 :(得分:0)

使用如下例所示的HashSet:

HashSet<String> hashTags = new HashSet<String>();
if(word.startsWith("#") && !hashTags.contains(word)){
  hashTag.add(word);
}

处理完推文后,hashTags将包含您看到的所有唯一哈希标记。你可以迭代它来获得它们。

相关问题