我将数据存储在路径中的文件中,例如:
/home/yamada/data/train/atheism/file_name.txt
我使用此数据填充哈希映射,存储数据的来源及其内容,如下所示。
/home/yamada/data/test/sports/t.s_1.txt, [0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]
/home/yamada/data/test/politics/t.p_0.txt, [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
/home/yamada/data/test/atheism/t.a_0.txt, [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
/home/yamada/data/test/science/t.s_0.txt, [1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0]
但是,我只希望将路径存储到目录点,而不是特定文件,如下所示:
/home/yamada/data/train/atheism
以下正则表达式命令能够根据regex101.com提取我感兴趣的组件:
(home\/yamada\/data\/train\/atheism)
我如何使用java模式匹配器来确保只将前面提到的字符串(包括目录的路径,而不是文件名)保存到哈希映射中?
模式匹配器是此操作的最佳选择吗?
下面是填充哈希映射的方法。
public static void perceptron_data_struc_generateur(Set<String> GLOBO_DICT,
Map<File, ArrayList<String> > fileDict,
Map<File, int[] > perceptron_input)
{
//create a new entry in the array list 'perceptron_input'
//with the key as the file name from fileDict
//create a new array which is the length of GLOBO_DICT
//iterate through the indicies of GLOBO_DICT
//for all words in globo dict, if that word appears in fileDict,
//increment the perceptron_input index that corresponds to that
//word in GLOBO_DICT by the number of times that word appears in fileDict
//so i can get the index later
List<String> GLOBO_DICT_list = new ArrayList<>(GLOBO_DICT);
for (Map.Entry<File, ArrayList<String>> entry : fileDict.entrySet())
{
int[] cross_czech = new int[GLOBO_DICT_list.size()];
//initialize to zero
Arrays.fill(cross_czech, 0);
for (String s : GLOBO_DICT_list)
{
for(String st : entry.getValue())
{
if( st.equals(s) )
{
cross_czech[ GLOBO_DICT_list.indexOf( s ) ] = cross_czech[ GLOBO_DICT_list.indexOf( s ) ] +1;
}
}
}
perceptron_input.put( entry.getKey() , cross_czech);
}
}
答案 0 :(得分:1)
比这简单得多:
String dir = filename.replaceAll("/[^/]*$", "");
答案 1 :(得分:0)
如果我正确理解您的问题,您只想找到以/
结尾的部分(文件名不会有)。在那种情况下
(\w+/)+
should do the trick(顺便说一下,我们不会在Java的正则表达式中转义/
)
但是,如果您的数据始终采用path/to/file
格式而您只想提取path/to
,那么您不需要正则表达式,您可以使用File类及其getParent
方法,例如< / p>
String data = new File("/home/yamada/data/train/atheism/file_name.txt").getParent();
System.out.println(data);
这将返回\home\yamada\data\train\atheism
,因此您将/
而不是\
,但如果您想在Java中使用此数据,这不应该是一个问题({{1} }接受两个分隔符。)