gpt4 book ai didi

java - 标签独特性

转载 作者:行者123 更新时间:2023-11-30 04:12:49 25 4
gpt4 key购买 nike

我试图从用户输入的推文中找到独特的主题标签。我哥哥正在帮助我,但他不得不离开。无论如何,我有代码来查找输入中使用单词的次数,但我只需要知道使用的不同主题标签的数量。例如,在输入“#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;
}

}}

最佳答案

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

我删除了您的字符串替换,因为我不确定您为什么要删除非单词字符 - 您将删除主题标签上的“#”。并且多个空格不是问题—— 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]

关于java - 标签独特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19215579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com