0

我有一个代码可以从文本文件中读取某些单词并将它们成对显示(取决于它们在段落中的出现 - 例如:

Hi I am <PER>Rita</PER>.I live in <LOC>Canada</LOC>
Hi I am <PER>Jane</PER> and I do not live in <LOC>Canada<LOC/> 

输出

丽塔加拿大
简加拿大

(注意:这不是 xml 文件。)
我希望输出对 (Rita Canada)=1 [因为它们之间有句号] 和 (Jane Canada)=0 [因为它们之间没有句号]
这里是我的代码以段落方式输出名称。你能帮我识别句号吗?

private static final Pattern personPattern = Pattern.compile("<PER>(.+?)</PER>");
private static final Pattern locationPattern = Pattern.compile("<LOC>(.+?)</LOC>");
for(File file : listOfFiles)
    {
        BufferedReader input = new BufferedReader(new FileReader(file));

        String line = "";
        while((line = input.readLine()) != null)
        {

            ArrayList<String> persons = new ArrayList<String>();
            ArrayList<String> locations = new ArrayList<String>();
            Matcher m_person = personPattern.matcher(line);
            while(m_person.find())
            {
                persons.add(m_person.group(1));

            }

            Matcher m_location = locationPattern.matcher(line);
            while(m_location.find())
            {
                locations.add(m_location.group(1));

            }


            for(int i = 0;i<persons.size();i++)
            {
                for(int j =0 ;j<locations.size();j++)
                {

                System.out.println(persons.get(i) + "\t" + locations.get(j));
                }

            }
4

1 回答 1

0

PER 标签总是在 LOC 标签之前吗?他们有时在不同的地方吗?

在下面的正则表达式中,我指定了一个积极的前瞻,其中包含一个与 a 匹配(?=)的原子组,如果不匹配,则匹配失败。(?>\.)\.

然后与第二个捕获组交替,以便在没有捕获组的情况下模式可以继续匹配\.

<PER>(.+?)</PER>(?=(?>\.))|<PER>(.+?)</PER>

捕获组 1:丽塔

捕获组 2:简

于 2013-12-11T04:19:11.117 回答