[英]Java Reading Words from a file with apostrophies and hypens and counting them as 2 words
[英]java - Reading specific words from a file
因此,我有一個動物園數據庫,游客可以在這里看到不同種類的動物。 每個訪客都有自己的日志,記錄了他看見了什么動物以及何時看見了。 我正在嘗試創建訪問者看到的所有動物的列表,並分離出訪問者的唯一ID。 如果訪客在不同的日子見過相同種類的動物,則將看到該動物的次數映射到該動物的名字。 我只需要列表中的動物名稱和其他處理目的的客戶ID。 日期並不重要。 這就是示例日志的樣子。
ClientId: 1001
Zebra 10/1
Cheetah 10/2
Tiger 10/2
Lion 10/3
Zebra 10/4
這是我的日志類:
public class Log {
private int clientId;
private int animalCount = 1;
private Map<String, Integer> animalList = new HashMap<String, Integer>();
public void addFromFile(String fileName) {
File file = new File(fileName);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
}
while (sc.hasNextLine()) {
sc = new Scanner(sc.nextLine());
String s = sc.next();
//Don't add the dates. Only the Strings
if (!isNumeric(s)) {
if (animalList.containsKey(s)) {
animalList.put(s, animalList.get(s) + 1);
} else {
animalList.put(s, animalCount);
}
}
}
}
public Map<String, Integer> getList() {
return animalList;
}
public int getClientId() {
return this.clientId;
}
public int itemCount() {
return this.itemCount;
}
public boolean isNumeric(String str) {
return Character.isDigit(str.charAt(0));
}
}
日志將始終按照該順序顯示。 我在先處理客戶ID行然后進行動物名稱處理時遇到了麻煩。
使用上面的示例日志的以下輸出為:
Log log = new Log();
log.addFromFile("DataSetOne1.txt");
System.out.println(log.getList());
//Output: {ClientId:=1}
我的代碼一直停留在第一行。 我希望能夠處理第一行並首先使其擺脫干擾,因為它包含了我所關心的唯一整數值。 我只是對如何解決這個問題感到困惑。
如果每個條目都位於單獨的行上,則循環遍歷chars直到找到digits
(數字)或:
chars,然后在每一行上將chars存儲在2D數組或列表中的數組中。
如果在一行上找到的字符為:
,則丟棄該行先前獲取的字符,並記錄該字符直到該行的末尾,使用String.trim()
可以獲取訪問者的ID。
否則,如果找到數字,則停止記錄字符,並退出該行的循環,並且再次在.trim()
,您應該具有動物的名稱。
PS:RegEx或Pattern-Matcher,較難理解(正如您在OP的評論中指出的那樣),但這樣做會更容易。 如果您想使用字符串或文件解析,則應該真的, 真的 , 真的 , 真的要學習這些知識。
最終弄明白了。 這不是最優雅的解決方案,但可以解決問題。
public void addFromFile(String fileName) {
File file = new File(fileName);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc.hasNextLine()) {
Scanner sc2 = new Scanner(sc.nextLine());
while (sc2.hasNext()) {
String s = sc2.next();
if (!isNumeric(s)) {
// Retrieve the client ID and assign it to the instance
// variable
if (s.equals("ClientId:")) {
clientId = Integer.parseInt(sc2.next());
}
if (animalList.containsKey(s)) {
animalList.put(s, animalList.get(s) + 1);
} else {
animalList.put(s, animalCount);
}
}
}
}
// Delete the ClientId entry
animalList.remove("ClientId:");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.