使用Python 2.6
我有一个很大的文本文件。 以下是前 3 个条目,但我需要检查超过 50 个用户。
html_log:jeff 1153.3 1.84 625:54 1 2 71 3 2 10 7:58 499 3 5 616:36 241 36 html_log:fred 28.7 1.04 27:34 -10 18 13 0:48 37 18 8 -3.63 html_log:bob 1217.1 1.75 696:48 1 5 38 6 109 61 14:42 633 223 25 435:36 182 34 ... continues
在本例中,我需要能够找到用户名,即“html_log:”标签后面的文本
我还需要评级(用户名旁边的第一组值。)
输出将检查整个txt文件并输出评分最高的前10名玩家。
请注意,并不总是有 16 组值,有些包含的值要少得多。
制作:
bob 1217.1
jeff 1153
fred 28.7
最佳答案
在这种情况下,我实际上会使用正则表达式。
只需将 html_log:
视为记录开始标记,下一部分直到空格就是名称。接下来的部分是分数,您可以将其转换为 float 进行比较:
s = "html_log:jeff 1153.3 1.84 625:54 1 2 71 3 2 10 7:58 499 3 5 616:36 241 36 html_log:fred 28.7 1.04 27:34 -10 18 13 0:48 37 18 8 -3.63 html_log:bob 1217.1 1.75 696:48 1 538 6 109 61 14:42 633 223 25 435:36 182 34"
pattern = re.compile("html_log:(?P<name>[^ ]*) (?P<score>[^ ]*)")
print sorted(pattern.findall(s), key=lambda x: float(x[1]), reverse=True)
# [('bob', '1217.1'), ('jeff', '1153.3'), ('fred', '28.7')]
关于python统计前10名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16846139/