如何计算特定单词在数组列表中出现的次数

huangapple go评论115阅读模式
英文:

How do I count the amount of times a specific word comes up in an array list

问题

import java.io.File;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Scanner;

public class Artists {

    public static ArrayList<String> artists = new ArrayList<String>();

    public static void main(String[] args) {
        System.out.println(readArtists("artists30.txt"));
        System.out.println(artists + "\n");
    }

    public Artists() {
    }

    public static boolean readArtists(String fileName) {
        Scanner sc = null;
        try {
            File file = new File(fileName);
            if (file.createNewFile()) {
                System.out.println("err " + fileName);
                return false;
            }
            sc = new Scanner(file);
            while (sc.hasNextLine()) {
                artists.add(sc.nextLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sc != null) {
            sc.close();
        }
        return true;
    }

    public int count() {
        int count = artists.size();
        return count;
    }

    public int count(String genre) {
        int genreCount = 0;
        for (String artistInfo : artists) {
            String[] parts = artistInfo.split(" ");
            if (parts.length >= 2 && parts[1].equalsIgnoreCase(genre)) {
                genreCount++;
            }
        }
        return genreCount;
    }
}
英文:

I have a class that takes in a txt file with artists and their genre in the format:
Abba Rock
Beethoven Classical

I am trying to write a method "public int count(String genre)" that counts the amount of times that word/genre is present. For example, for rock, it would need to count the number of rock artists and satisfy my test case:

public class ArtistTest
{
public static void main(String[] args)
{    
Artists artists = new Artists();
System.out.println(artists.count() + &quot; artists in the list&quot;);
System.out.println(artists.count(&quot;Rock&quot;) + &quot; rock artists in the list\n&quot;);

My initial count method successfully counts the number of artists (I guess there would be a better way to do that)

My code so far:

import java.io.File;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Scanner;
public class Artists {
public static ArrayList&lt;String&gt; artists = new ArrayList&lt;String&gt;();
public static void main(String[] args) {
System.out.println(readArtists(&quot;artists30.txt&quot;));
System.out.println(artists + &quot;\n&quot;);
}
public Artists() {
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println(&quot;err &quot; + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
artists.add(sc.nextLine());
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
int count = artists.size();
return count;
}
public int count(String genre) {
}
}

What I'm testing with:

public class ArtistTest
{
public static void main(String[] args)
{    
Artists artists = new Artists();
System.out.println(artists.count() + &quot; artists in the list&quot;);
System.out.println(artists.count(&quot;Rock&quot;) + &quot; rock artists in the list\n&quot;);
System.out.println(&quot;File opened successfully? &quot; + artists.readArtists(&quot;artists30.txt&quot;));
System.out.println(&quot;\n&quot; + artists.count() + &quot; artists in the list&quot;);
System.out.println(artists.count(&quot;Rock&quot;) + &quot; rock artists in the list&quot;);
System.out.println(artists.count(&quot;R&amp;B&quot;) + &quot; R&amp;B artists in the list&quot;);
}
}

答案1

得分: 1

这是您要求的翻译内容:

我是老派的。所有那些新的 Streams 相关的东西让我感到晕头转向。我喜欢保持事情简单。我达到您想要的目标的方法是做两件简单的事情:
1)定义一个表示每位艺术家信息的 Artist 对象。此对象知道如何根据数据文件中的一行构造自身。
2)在读取艺术家的同时,创建一个按流派分类的第二个索引,该索引将为每个流派提供一个艺术家列表。
我做的另一件事是使事情变得非静态,这样您实际上可以实例化一个 Artists 对象,以防您希望拥有多个艺术家列表。
以下是我的版本:
import java.util.*;
import java.io.File;
import java.util.Scanner;
public class Artists {
public class Artist {
public String name;
public String genre;
public Artist(String line) {
String[] parts = line.trim().split("\\s+");
name = parts[0];
genre = parts[1];
}
}
private List<Artist> artists = new ArrayList<>();
private Map<String, List<Artist>> genres = new HashMap<>();
public boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("err " + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
// 将行转换为 Artist 对象
Artist artist = new Artist(sc.nextLine());
// 将其添加到主要的艺术家列表中
artists.add(artist);
// 将其添加到按流派分类的索引中
if (!genres.containsKey(artist.genre))
genres.put(artist.genre, new ArrayList<>());
genres.get(artist.genre).add(artist);
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
return artists.size();
}
public int count(String genre) {
if (genres.containsKey(genre))
return genres.get(genre).size();
return 0;
}
public static void main(String[] args) {
Artists artists = new Artists();
String filepath = "/tmp/artists30.txt";
if (artists.readArtists(filepath)) {
System.out.printf("Artist Count: %d\n", artists.count());
System.out.printf("Rock Artist Count: %d\n", artists.count("Rock"));
}
else {
System.out.printf("Failed to read artists file '%s'\n", filepath);
}
}
}
示例数据:
Abba Pop
Beethoven Classical
Rush Rock
Aerosmith Rock
Mozart Classical
AC/DC Rock
Yes Rock
结果:
艺术家数量:7
摇滚音乐家数量:4
英文:

I'm old school. All that new Streams stuff spins my head around. I like to keep things simple. My way to what you want is to do two simple things:

  1. Define an Artist object that will represent the info on each artist. This object knows how to construct itself from a line in the data file.

  2. While reading in the artists, create a second by-genre index that will give you a list of artists for each genre.

The other thing I did was make things non-static, so you actually instantiate an Artists object, in case you ever wanted to have multiple lists of artists.

Here's my rendition:

import java.util.*;
import java.io.File;
import java.util.Scanner;
public class Artists {
public class Artist {
public String name;
public String genre;
public Artist(String line) {
String[] parts = line.trim().split(&quot;\\s+&quot;);
name = parts[0];
genre = parts[1];
}
}
private List&lt;Artist&gt; artists = new ArrayList&lt;&gt;();
private Map&lt;String, List&lt;Artist&gt;&gt; genres = new HashMap&lt;&gt;();
public boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println(&quot;err &quot; + fileName);
return false;
}
sc = new Scanner(file);
while (sc.hasNextLine()) {
// Turn the line into an Artist object
Artist artist = new Artist(sc.nextLine());
// Add it to the main list of artists
artists.add(artist);
// Add it to the per-genre index
if (!genres.containsKey(artist.genre))
genres.put(artist.genre, new ArrayList&lt;&gt;());
genres.get(artist.genre).add(artist);
}
} catch (Exception e) {
e.printStackTrace();
}
if (sc != null) {
sc.close();
}
return true;
}
public int count() {
return artists.size();
}
public int count(String genre) {
if (genres.containsKey(genre))
return genres.get(genre).size();
return 0;
}
public static void main(String[] args) {
Artists artists = new Artists();
String filepath = &quot;/tmp/artists30.txt&quot;;
if (artists.readArtists(filepath)) {
System.out.printf(&quot;Artist Count: %d\n&quot;, artists.count());
System.out.printf(&quot;Rock Artist Count: %d\n&quot;, artists.count(&quot;Rock&quot;));
}
else {
System.out.printf(&quot;Failed to read artists file &#39;%s&#39;\n&quot;, filepath);
}
}
}

Sample Data:

Abba Pop
Beethoven Classical
Rush Rock
Aerosmith Rock
Mozart Classical
AC/DC Rock
Yes Rock

Result:

Artist Count: 7
Rock Artist Count: 4

答案2

得分: 0

以下是翻译好的代码部分:

只要您的映射为"artist" + "space" + "genre"您可以尝试以下代码这将创建一个映射其中所有流派都作为键值是该流派的相应计数

class Grouper {

public static void main(String[] args) {
    var grouper = new Grouper();
    grouper.groupByGenre();
}

void groupByGenre() {
    List<String> musicCollection = List.of("Kid Rock", "Hello Rock", "Beethoven Classical");
    var collection = musicCollection.stream()
            .map(entry -> entry.split(" "))
            .filter(strings -> strings.length == 2)
            .map(strings -> new MusicCollection(strings[0], strings[1]))
            .collect(Collectors.groupingBy(MusicCollection::getGenre, Collectors.counting()));
    System.out.println(collection);
}
}

class MusicCollection {
private final String artist;
private final String genre;

public MusicCollection(String artist, String genre) {
    this.artist = artist;
    this.genre = genre;
}

public String getArtist() {
    return artist;
}

public String getGenre() {
    return genre;
}
}

EDIT:
为了使它更简单将您的计数方法替换为以下内容

public int count(String genre)
{
    return (int) artists.stream()
            .map(entry -> entry.split(" "))
            .filter(strings -> strings.length == 2)
            .map(strings -> strings[1])
            .filter(value -> Objects.equals(value, genre))
            .count();
}

请注意,已经将代码中的HTML实体编码转换为正常文本。

英文:

Well as long as your mapping will be "artist" + "space" + "genre" you could try the following code. This creates a map with all the genres as key, and the value is the respective count for the genre.

class Grouper {
public static void main(String[] args) {
var grouper = new Grouper();
grouper.groupByGenre();
}
void groupByGenre() {
List&lt;String&gt; musicCollection = List.of(&quot;Kid Rock&quot;, &quot;Hello Rock&quot;, &quot;Beethoven Classical&quot;);
var collection = musicCollection.stream()
.map(entry -&gt; entry.split(&quot; &quot;))
.filter(strings -&gt; strings.length == 2)
.map(strings -&gt; new MusicCollection(strings[0], strings[1]))
.collect(Collectors.groupingBy(MusicCollection::getGenre, Collectors.counting()));
System.out.println(collection);
}
}
class MusicCollection {
private final String artist;
private final String genre;
public MusicCollection(String artist, String genre) {
this.artist = artist;
this.genre = genre;
}
public String getArtist() {
return artist;
}
public String getGenre() {
return genre;
}

}

EDIT:
To make it simpeler, replace your count method with the following:

    public int count(String genre)
{
return (int) artists.stream()
.map(entry -&gt; entry.split(&quot; &quot;))
.filter(strings -&gt; strings.length == 2)
.map(strings -&gt; strings[1])
.filter(value -&gt; Objects.equals(value, genre))
.count();
}

huangapple
  • 本文由 发表于 2020年10月6日 14:25:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64220397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定