python - 具有多列的文本文件中的最大值
问题描述
做了一些计算后,我有一个格式为的文本文件:
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
解决方案
这是我的解决方案
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
推荐阅读
- rust - 如何避免在许多点上存在少量差异的类似方法中的代码重复?
- javascript - Vue.js - 绑定到组件的道具未显示正确的结果
- c# - 从 Angular JS 1.6 中 view.html 文件中的 js 文件中读取一个字段
- vue.js - 如何使用 vuepress 站点修复下拉项上的导航栏重叠
- mongodb - 排除特定测试的 embedded.mongodb.enabled
- sql - 获取所有符合条件Oracle SQL的记录
- javascript - JSS 中的 MUI 全局类名称有多可靠?
- oracle - 如何创建触发器以将所有 DML 存储在 oracle 中?
- c++ - 使用 Qt 库在 C++ 中解析 json 数据
- javascript - 如何将对象内部的所有键值组合到es6中的新数组中