简体   繁体   English

根据第N个单词对句子排序

[英]Sort sentences based on the Nth word

I have to read a file with one sentence on each line. 我必须阅读每行只有一个句子的文件。
Then I have to sort these sentences based on the N th word (I am given a number as an input parameter which represents the place of the sort-by-this word in the sentence). 然后,我必须根据第N 单词对这些句子进行排序(给我一个数字作为输入参数,该数字表示单词在该句子中的排序位置)。

File reading is done and I have loaded the words in a two-dimensional string array. 文件读取完成,我将单词加载到二维字符串数组中。

for(String line : Files.readAllLines(file))
for(String word : line.trim().split(" "))

How should I sort the sentences? 我应该如何对句子排序?

Use a custom Comparator<String> , to parametrize your sort invocation (invoked on either a Collection or an Array , through the Collections or Arrays utility classes respectively). 使用定制的Comparator<String> ,进行参数的sort (调用在任一个调用Collection或一个Array ,通过CollectionsArrays分别实用类)。

  • You will need to have an instance field in your Comparator , that will represent the Nth word's index you base your sorting on, and a setter or constructor to set it 您将需要在Comparator具有一个实例字段,该实例字段将代表您基于其排序的Nth单词的索引,以及一个用于设置它的设置器或构造函数
  • In your compare(String s1, String s2) override, you will use that field to check whether both String s are long enough and have enough actual words (then, also decide what to do if either doesn't qualify) 在您的compare(String s1, String s2)覆盖中,您将使用该字段来检查两个String都足够长并且具有足够的实际单词(然后,如果两个都不符合条件,则还要决定怎么做)
  • If both String s qualify, you will pick those words by itemizing them through a Scanner or Pattern , and return the computation of compare on those two words, instead of the whole String s 如果两个String符合条件,则可以通过ScannerPattern逐项列出这些单词,然后返回对这两个单词而不是整个Stringcompare计算。
  • That will guarantee that given a list of String s and a word index, all String s qualifying to have a separable word at that given word index will be compared based on the lexicographical comparison of those words, and a separate logic for those String s that do not qualify 这将确保在给定String列表和单词索引的情况下,将根据这些单词的词典顺序比较来比较所有在该给定单词索引处具有可分离单词的合格String ,以及针对这些String的单独逻辑,不符合条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM