[英]line sorting by using python
我有一個包含如下行的txt文件(第一個字段是關鍵字,第二個字段是關鍵字的頻率,第三個字段是相關文本):
anorexia nervosa 1 在专利网看到一
glaucoma 10 want to suck out my eyeballs and have them replaced with
cancer 691 there is a drug that helps fight cancer called avastin
gene therapy 1 writing a review paper on gene therapy
hormone 35 glad my hormone injections end in a month
depression 259 depression? just made depression cake: recipe here
我想像這樣解析文件(按關鍵字頻率排序的關鍵字):
cancer 691
depression 259
hormone 35
glaucoma 10
anorexia nervosa 1
gene therapy 1
我檢查有關排序和訂單問題的其他問題,但我找不到任何好的例子。 sort()似乎沒有用。 請讓我知道好的起點!
如果你的行在一個數組中,使用key
參數到sort函數; lambda將在空格/制表符處分割線,取第二列,轉換為float並將其用於比較。 reverse
導致順序下降(抱歉,未經測試,但99%的模擬輸入錯誤):
data=file(yourFile).readlines()
data.sort(key=lambda l: float(l.split()[1]),reverse=True)
eudoxos的解決方案可以工作,你必須用標簽分開(\\ t)即。,
data=file(yourFile).readlines()
data.sort(key=lambda l: float(l.split('\t')[1]),reverse=True)
在這里,通過輸入文本的外觀,我假設,不同的字段由制表符分隔。
但是,用逗號分隔將是一個更好的解決方案,因為,有可能混合制表符和空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.