如何读取夹在某个字符之间的数据(Python 3.3)

时间:2015-05-09 11:41:30

标签: python python-3.x

好的,从技术上讲,我已经分配了一个完成的任务,它涉及循环(而for,for等),我遇到了一个问题:

我被要求以这样的列表格式存储分数和用户名,级别等:

# <username>, <level>, <level_score> - Like this: 
['buzzysin,5,100','apple_maple,3,60','choco_charlie,2,25','buzzysin,1,10']

我需要做的是使用这些数据创建记分牌,但我似乎无法将分数与列表中的字符串隔离开来。以下是我的代码片段:

def scoreboard():
    name = input("Enter a username: ") # Say 'buzzysin'
    t = open('scores.txt', 'r')
    a = t.readlines()
    b = [] 
    t.close()
    for i in range(len(a)):
        if name not in a[i]:
            pass
        else: # Here I need to get the occurences of 'buzzysin' and append it to b
            b.append(a[i])
    #Then I need to extract the level and scores, but here's where I'm stuck :-(

我的记分牌需要如下所示:

>>> scoreboard()
Please enter a name: buzzysin
The scores for buzzysin are:

    Level    Scores
-----------------------
      1        10
      2         0
      3         0
      4         0
      5       100

>>>

请帮忙,

'buzzysin'

4 个答案:

答案 0 :(得分:2)

首先,for i in len(a)将引发异常,因为整数不可迭代。您应该直接迭代a或迭代像range(len(a))这样的索引列表。其次,如果a中的行格式如下buzzysin,5,100,则应使用string.startswith in的整数(节省了大量时间)。然后,如果字符串以buzzysin开头,则可以使用string.split(',')解析该字符串以获得分数。例如,

for line in a:
    if line.startswith(player_name):
        name, level, score = line.rstrip().split(',')

答案 1 :(得分:0)

只需使用.split(',')

lines = ['buzzysin,5,100','apple_maple,3,60','choco_charlie,2,25','buzzysin,1,10']
for line in lines:
    name, level, score = line.split(',')
    print(name, 'is in level', level, 'with score', score)

打印:

buzzysin is in level 5 with score 100
apple_maple is in level 3 with score 60
choco_charlie is in level 2 with score 25
buzzysin is in level 1 with score 10

答案 2 :(得分:0)

去模块化!编写一个单独的函数来解析每一行,用它来解析所有行,然后过滤掉相关人员的分数。列表理解对此非常有用:

def parse_line(line):
    """parse a score line, returning its data

    A score line is of the form: <username>,<level>,<level_score>

    The level and score are integers.
    """
    parts = line.split(',')
    if len(parts) != 3:
        return None # or raise an exception
    name = parts[0]
    level = int(parts[1])
    level_score = int(parts[2])
    return name, level, level_score

# read the lines
with open('scores.txt', 'r') as t:
    lines = t.readlines()

# parse the lines, ignoring empty lines
scores = [parse_line(line) for line in lines if line != ""]

# get the person's name
name = input("Enter a username: ") # Say 'buzzysin'

# filter that person's scores
persons_scores = [score for score in scores if score[0] == name]

# now print your table...

答案 3 :(得分:0)

# get all scoreboard data
data = ['buzzysin,5,100','apple_maple,3,60','choco_charlie,2,25','buzzysin,1,10']
# get target name
target_name = input("Enter a username: ")
# initialize our target scoreboard
target_scoreboard = {}
# get scoreboard data for our target
for name_data in data: # look at all the data, one item at a time
    if name_data.split(',')[0] == target_name:
        # if this data is for our target, add it to out target scoreboard
        level = int(name_data.split(',')[1])
        score = int(name_data.split(',')[2])
        target_scoreboard[level] = score

# print scoreboard for our target, sorted by level
print("\tLevel\tScore")
print("-"*25)
for level in sorted(target_scoreboard):
    print('\t{:d}\t{:d}'.format(level, target_scoreboard[level]))