2014-11-20 3 views
0

는이 같은 .txt 인 파일이 :파이썬에서 파일의 텍스트를 정렬하는 방법은 무엇입니까?

나는 다른 목록에서 하나의 목록에서 자신의 값을 비교하여 상위 3 개 단어와 나머지 단어를 표시 할
ancient 0.4882 
detained 5.5512 
neighboring 2.9644 
scores 0.5951 
eggs 0.918 
excesses 3.0974 
proceedings 0.7446 
menem 1.7971 

.

즉,이 예를 들어 출력이되어야한다 :

[detained, excesses, neighboring] & [menem, eggs, proceedings, scores, ancient]

어떻게 할까?

편집 :

내가 한 가지를 언급하는 것을 잊었다 : 그 작업을 수행하는 방법에 0.5 이상의 큰 값을 가질 만 단어를 고려하는 것이 좋습니다? CSV를 사용

+0

어디서 붙어 있습니까? 파일을 열고 읽는 방법을 알고 있습니까? – monkut

+0

@monkut Ya, 나는 한 가지리스트에 모든 단어가 있고, 두 번째리스트에는 모든 float 값이 있고, 두 번째리스트를 정렬하는 것과 비슷한 것을하고 있었다.하지만 나는 잃어 버렸다. –

답변

1
import csv 
with open('x.txt') as f: 
    # use space as delimiter 
    reader = csv.reader(f, delimiter=' ') 
    # sort by the value in the second place of each line i.e. x[1] 
    s = sorted(reader, key=lambda x: x[1], reverse=True) 
    # filter only grater than 0.5 and take the first value only 
    l = [x[0] for x in s if float(x[1])>0.5] 
    print l[:3] 
    print l[3:] 
+0

나는 내가 묻는 것을 잊었던 또 하나의 물건을 가지고 있었다. 그걸 도와 줄 수있어? –

+0

0.5보다 큰 값을 가진 단어 만 생각하고 싶습니다. 어떻게합니까? –

1
import csv  
with open('inputFile.csv','r') as inputFile: 
    reader = csv.reader(inputFile, delimiter = " ")  
    word = dict()  
    for line in reader: 
     if float(line[1]) > 0.5: 
      word[line[0]] = float(line[1]) 

    sortedArray = sorted(word.iteritems(), key=lambda x:-x[1]) 
    maxWords = sortedArray[:3] 
    Remaining = sortedArray[3:]  
    print maxWords 
    print Remaining 
+0

당신도 이것을 설명 할 수 있다면 좋을 것입니다. 나는 .txt 파일이 아니라 .csv 파일이 있습니다. –

+1

한 번만 정렬 할 수 있습니다. 'sorted_words = sorted (word.iteritems(), key = lambda x : -x [1])'와'max_words = sorted_words [: 3]'및'remaining = sorted_words [3 :]'와 같은 것입니다. – Hamatti

+0

한 가지 더 말씀해 주시겠습니까? 0.5보다 큰 가치가있는 단어 만 고려하고 싶습니다. 어떻게해야합니까? –

1

대답은 나보다 더 간결하지만 여기에 또 다른 접근 방식이다.

from operator import itemgetter 

with open('file_list_data.txt', 'r') as f: 
    lines = f.readlines() 

records = [l.split() for l in lines] 
records_with_numbers = [(r[0], float(r[1])) for r in records if float(r[1]) > 0.5] 

sorted_records = sorted(records_with_numbers, key=itemgetter(1), reverse=True) 

top_3 = [word for (word, score) in sorted_records[0:3]] 
rest = [word for (word, score) in sorted_records[3:]] 
+0

0.5보다 큰 값을 가진 단어 만 생각하고 싶습니다. 어떻게해야합니까? –

+0

변수 records_with_numbers를 생성 할 때 값이 0.5보다 큰 단어 만 유지하는 필터를 추가했습니다. –

관련 문제