首页 > 解决方案 > 具有多列的文本文件中的最大值

问题描述

做了一些计算后,我有一个格式为的文本文件

word1 word2 0.1111 hyp1 hyp2 0.1111111111111111
word3 word4 0.2 hyp3 hyp4 0.07692307692307693
word5 word6 0.2 hyp5 hyp6 0.3333333333333333

所以这有 6 列,两个有值的词,然后是 2 个有值的上位词。

我的目标是获得前 10 个最高值对并写入文件(不是我正在努力的部分)

我的问题是我应该采取什么方法,以便它查看第 3 列和第 6 列,然后将文件列 1、2、3 或 4、5、6 放入文件中。所以我可能会得到一个看起来像的文本文件:

chapter tom 0.08333333333333333 section black 0.1
answer tom 0.09090909090909091 statement black 0.1111111111111111
boy wonder 0.08333333333333333 man astonishment 0.09090909090909091
tom answer 0.09090909090909091 turkey statement 0.058823529411764705
old lady 0.08333333333333333 past woman 0.1
pulled spectacle 0.1111111111111111 tear sight 0.1111111111111111

标签: pythoniomax

解决方案


这是我的解决方案

import re

def my_sort(val):
    pattern = r'[0-9]+\.[0-9]+'
    p = re.findall(pattern, val)
    return float(p[0])

with open('test.txt', 'r') as f:
    txt = f.read()

pattern1 = r'[a-z]+[0-9]* [a-z]+[0-9]* [0-9]+\.[0-9]+'
p1 = re.findall(pattern1,txt)
p1.sort(key=my_sort)
result = p1[::-1]

with open('text2.txt','w') as f:
    for i in result:
        f.write(i+'\n')

文件 text2.txt 中的输出是

hyp5 hyp6 0.3333333333333333
word5 word6 0.2
word3 word4 0.2
hyp1 hyp2 0.1111111111111111
word1 word2 0.1111
hyp3 hyp4 0.07692307692307693

另一个例子:

tear sight 0.1111111111111111
pulled spectacle 0.1111111111111111
statement black 0.1111111111111111
past woman 0.1
section black 0.1
tom answer 0.09090909090909091
man astonishment 0.09090909090909091
answer tom 0.09090909090909091
old lady 0.08333333333333333
boy wonder 0.08333333333333333
chapter tom 0.08333333333333333
turkey statement 0.058823529411764705

推荐阅读