我有一个数学计划,即对球员进行评分并输入他们的名字并将其分数到文本文件中。
我可以从文本文件中获取分数,但无法确定如何识别每个部分:名称为字符串,分数为int。
输入到这样的文件:
playername: 8
输入玩家姓名和得分到文本文件的代码是:(我已将得分设置为全局变量,并且它是从之前的函数中提取的。
# write score to text document
def scores():
score = Pname + ": " +str(points)
scoreFile = open("score.txt", "a")
scoreFile.write(score + "\n")
scoreFile.close()
print("Your scores have been saved to the high score chart.\n")
close()
我试图解决它的多种方式只是给我数据。我努力将其拆分为名称和得分,然后按得分降序排列。
def highscore():
# --------------------------------------------
# sort scores from text file here
try:
scores = open("score.txt", "r")
for line in scores.readlines():
line_parts = line.split(": ")
if len(line_parts) > 1:
line_parts = line_parts[-1].split("\n")
score = line_parts[0]
print(sorted(score))
except Exception:
pass
# --------------------------------------------
close()
这只是显示如下分数:
['7']
['4']
['9']
['1']
我需要的是:
['Player 1: 9']
['Player 2: 7']
['Player 3: 4']
['Player 4: 1']
答案 0 :(得分:0)
试试这个: 创建一个排序方法并将整个列表提供给soreted方法。
public static class addProjInfo_container {
public static String projName_txt(WebDriver driver) {
By by = By.xpath("//label[text()='Project Name']/following-sibling::input");
driver.findElement(by);
return getSelectorAsString(by);
}
public static String getSelectorAsString(By by) {
String str = by.toString();
return str.substring(str.indexOf(" ") , str.length());
}
// and so on for every text field for adding project...
}
<强>更新强>
我已更新代码并对其进行了测试。现在它有效。我一直在使用python2.7
更新:2
这很简单。只需将def highscore():
# --------------------------------------------
# sort scores from text file here
try:
scores = open("score.txt", "r")
x = [] # place all your processed lines in here
for line in scores.readlines():
line_parts = line.split(": ")
if len(line_parts) > 1:
line_parts[-1] = line_parts[-1].replace("\n", "")
x.append(line_parts) # sorting uses lists
print(sorted(x, key=sortByScore)) # get this out of for loop
except Exception:
pass
# --------------------------------------------
close()
def sortByScore(inputPlayerScore):
return inputPlayerScore[1]
命令移出print
循环,您就可以获得所需的输出。