gpt4 book ai didi

java - 使用Java根据关键字解析文本

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:03:10 26 4
gpt4 key购买 nike

基本上,我得到了一个包含人员详细信息的文件,每个人都用新行分隔,例如"

name Marioka address 97 Garderners Road birthday 12-11-1982 \n
name Ada Lovelace gender woman\n
name James address 65 Watcher Avenue

”等等..

而且,我想将它们解析为 [Keyword : Value] 对数组,例如

{[Name, Marioka], [Address, 97 Gardeners Road], [Birthday, 12-11-1982]},
{[Name, Ada Lovelace], [Gender, Woman]}, and so on....

等等。关键字将是一组定义的词,在上面的例子中:姓名、地址、生日、性别等...

执行此操作的最佳方法是什么?

我就是这样做的,它有效但想知道是否有更好的解决方案。

    private Map<String, String> readRecord(String record) {
Map<String, String> attributeValuePairs = new HashMap<String, String>();
Scanner scanner = new Scanner(record);
String attribute = "", value = "";

/*
* 1. Scan each word.
* 2. Find an attribute keyword and store it at "attribute".
* 3. Following words will be stored as "value" until the next keyword is found.
* 4. Return value-attribute pairs as HashMap
*/

while(scanner.hasNext()) {
String word = scanner.next();
if (this.isAttribute(word)) {
if (value.trim() != "") {
attributeValuePairs.put(attribute.trim(), value.trim());
value = "";
}
attribute = word;
} else {
value += word + " ";
}
}
if (value.trim() != "") attributeValuePairs.put(attribute, value);

scanner.close();
return attributeValuePairs;
}

private boolean isAttribute(String word) {
String[] attributes = {"name", "patientId",
"birthday", "phone", "email", "medicalHistory", "address"};
for (String attribute: attributes) {
if (word.equalsIgnoreCase(attribute)) return true;
}
return false;
}

最佳答案

要从字符串中提取值,请使用正则表达式。我希望您知道如何从文件中读取每一行以及如何用结果构建一个数组。

这仍然不是一个好的解决方案,因为如果名称或地址中包含任何关键字,它就不起作用......但这正是你所要求的......

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

public static void main(String[] args) {

Pattern p = Pattern.compile("name (.+) address (.+) birthday (.+)");

String text = "name Marioka address 97 Garderners Road birthday 12-11-1982";

Matcher m = p.matcher(text);

if (m.matches()) {
System.out.println(m.group(1) + "\n" + m.group(2) + "\n"
+ m.group(3));
} else {
System.out.println("String does not match");
}
}
}

关于java - 使用Java根据关键字解析文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13030157/

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