[英]Populate 2D array from input text file
我有一個數據語料庫,其中充滿了以下形式的實例:
'be in'('force', 'the closed area').
'advise'('coxswains', 'mr mak').
'be'('a good', 'restricted area').
'establish from'('person \'s id', 'the other').
我想從.txt文件中讀取此數據,並僅用單引號內的信息填充2D數組,即
be in [0][0], force [0][1], the closed area [0][2]
advise [1][0], coxswains [1][1], mr mak [1][2]
be [2][0], a good [2][1], restricted area [2][2]
establish from [3][0], person \'s id [3][1], the other [3][2]
^這些數組索引作為概念性引用存在於此,正如我上面所說的,僅單引號中的信息是可取的,例如,索引[0] [0]將be in
,索引[3] [1]將在其中person \\'s id
但是與示例索引[3] [1]一樣,我們可能在單引號前加上反斜杠,但不應將其解釋為定界符。
到目前為止,這是我所擁有的:
BufferedReader br_0 = new BufferedReader(new FileReader("/home/matthias/Workbench/SUTD/2_January/Prolog/horn_data_test.pl"));
String line_0;
while ((line_0 = br_0.readLine()) != null)
{
String[] items = line_0.split("'");
String[][] dataArray = new String [3][262978];
int i;
for (String item : items)
{
for (i = 0; i<items.length; i++)
{
if (i == 0)
{
System.out.println("first arg: " + items[i]);
}
if (i == 1)
{
System.out.println("first arg: " + items[i]);
}
if (i == 2)
{
System.out.println("second arg: " + items[i]);
}
}
}
}
br_0.close();
我知道我需要類似的東西:
if (the character under consideration == ' && the one before it is not \)
put it into first index, etc. etc.
但是如何使它在下一個定界符之前停止呢? 填充該數組的最佳方法是什么? 輸入文件很大,因此我正在嘗試優化效率。
您可以像這樣將regex與Pattern
和Matcher
一起使用:
public static void main(String[] args) throws IOException {
String[] stringArr = { "'be in'('force', 'the closed area').",
"'advise'('coxswains', 'mr mak').",
"'be'('a good', 'restricted area').",
"'establish from'('person \'s id', 'the other')." };
int i = 0;
Pattern p = Pattern.compile("'(.*?)'(?![a-zA-Z])");
String[][] arr = new String[4][3];
for (int count = 0; count < stringArr.length; count++) {
Matcher m = p.matcher(stringArr[count]);
int j = 0;
while (m.find()) {
arr[i][j++] = m.group(1);
}
i++;
}
for (int k = 0; k < arr.length; k++) {
for (int j = 0; j < arr[k].length; j++) {
System.out.println("arr[" + k + "][" + j + "] " + arr[k][j]);
}
}
}
O / P:
arr[0][0] be in
arr[0][1] force
arr[0][2] the closed area
arr[1][0] advise
arr[1][1] coxswains
arr[1][2] mr mak
arr[2][0] be
arr[2][1] a good
arr[2][2] restricted area
arr[3][0] establish from
arr[3][1] person 's id
arr[3][2] the other
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.