如何在python中对文件中的文本进行排序?

2024-06-17 08:14:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个.txt文件:

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的词怎么做?你知道吗


Tags: 文件txt编辑列表单词eggs例子amp
3条回答

使用csv的答案比我的更简洁,但这里有另一种方法。你知道吗

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:]]
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
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:]

相关问题 更多 >