0

我想读取一个输入文件并将句子转换为单词,然后提供一个唯一的整数 id。

我能够将输入字符串转换为单词,但我很困惑如何为每个单词分配唯一的 ID,并且需要删除重复项。(如果输入 - 我想去康提。两个场合'to'都应该得到相同的id)

这是我的代码:

Scanner sc = new Scanner(System.in);

System.out.println("enter the word");

String s= sc.nextLine();
String st[] =s.split(" ");
   for(int i=0;i<st.length-1 ;i++)
   {
        System.out.println(st[i]);
   }
4

2 回答 2

1

尝试

 public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        HashMap<Integer, String> store = new HashMap<Integer,String>();

        System.out.println("enter the word");

        String s= sc.nextLine();
        String st[] =s.split(" ");
        Integer uniqueId=1;

        for(int i=0;i<st.length;i++)
        {
            if(!store.values().contains(st[i])){
                store.put(uniqueId, st[i] );
                uniqueId = uniqueId+1;
            }                               
         }

         for (Integer id: store.keySet()){
             String key =id.toString();
             String value = store.get(id).toString();  
             System.out.println(key + " " + value);  

            }
         sc.close();
        }   

    }
于 2013-11-03T10:28:53.433 回答
1

为此,您可以使用 UUID 和 HashMap:

Map<String, String> map = new HashMap<String, String>(); // storage for all word-id pairs

/* here insert your resulting array from scanner and split as collectionOfWords */
for (String yourNextWord : collectionOfWords) {

String id = UUID.randomUUID();      // this one generates a unique string id
map.put(yourNextWord, id);

}

在此过程中,hashmap 将重复项替换为键,因此对于 1 个单词的多个副本,您将始终拥有 1 个且相同的条目。因此,它们的 id 将是相同的。

于 2013-11-03T10:23:42.483 回答