我需要从文本文件的行中提取数据。数据是名称和评分信息,格式如下:
Shyvana - 12/4/5 - Loss - 2012-11-22
Fizz - 12/4/5 - Win - 2012-11-22
Miss Fortune - 12/4/3 - Win - 2012-11-22
这个文件是由我的小python程序的另一部分生成的,我要求用户输入名称,查找他们输入的名称以确保它从名单列表中有效,然后请求杀戮,死亡,助攻和他们是赢还是输?然后我要求确认并将该数据写入新行的文件中,并将日期附加到最后。准备该数据的代码:
data = "%s - %s/%s/%s - %s - %s\n" % (
champname, kills, deaths, assists, winloss, timestamp)
基本上我想把这些数据读回到程序的另一部分并显示给用户,然后用它来计算特定名称随时间的平均值。
我是python的新手,而且我对编程一般都不是很有经验,所以我发现的大多数字符串拆分和格式化示例对我来说太过神秘了解如何适应我需要的东西,有人可以帮忙吗?我可以不同地格式化写入的数据,因此令牌查找会更简单,但我希望它直接在文件中简单。
答案 0 :(得分:10)
以下内容将所有内容都读入由播放器名称键入的字典中。与每个玩家相关联的值本身就是一个字典,作为记录,其中的命名字段与转换为适合进一步处理的格式的项目相关联。
info = {}
with open('scoring_info.txt') as input_file:
for line in input_file:
player, stats, outcome, date = (
item.strip() for item in line.split('-', 3))
stats = dict(zip(('kills', 'deaths', 'assists'),
map(int, stats.split('/'))))
date = tuple(map(int, date.split('-')))
info[player] = dict(zip(('stats', 'outcome', 'date'),
(stats, outcome, date)))
print('info:')
for player, record in info.items():
print(' player %r:' % player)
for field, value in record.items():
print(' %s: %s' % (field, value))
# sample usage
player = 'Fizz'
print('\n%s had %s kills in the game' % (player, info[player]['stats']['kills']))
输出:
info:
player 'Shyvana':
date: (2012, 11, 22)
outcome: Loss
stats: {'assists': 5, 'kills': 12, 'deaths': 4}
player 'Miss Fortune':
date: (2012, 11, 22)
outcome: Win
stats: {'assists': 3, 'kills': 12, 'deaths': 4}
player 'Fizz':
date: (2012, 11, 22)
outcome: Win
stats: {'assists': 5, 'kills': 12, 'deaths': 4}
Fizz had 12 kills in the game
或者,不是将大部分数据保存在字典中,而是可以使嵌套字段访问变得有点尴尬 - info[player]['stats']['kills']
- 您可以使用更高级的“通用”类来保存它们,让你改写info2[player].stats.kills
。
为了说明,使用我命名为Struct
的类几乎是一样的,因为它有点像C语言的struct
数据类型:
class Struct(object):
""" Generic container object """
def __init__(self, **kwds): # keyword args define attribute names and values
self.__dict__.update(**kwds)
info2 = {}
with open('scoring_info.txt') as input_file:
for line in input_file:
player, stats, outcome, date = (
item.strip() for item in line.split('-', 3))
stats = dict(zip(('kills', 'deaths', 'assists'),
map(int, stats.split('/'))))
victory = (outcome.lower() == 'win') # change to boolean T/F
date = dict(zip(('year','month','day'), map(int, date.split('-'))))
info2[player] = Struct(champ_name=player, stats=Struct(**stats),
victory=victory, date=Struct(**date))
print('info2:')
for rec in info2.values():
print(' player %r:' % rec.champ_name)
print(' stats: kills=%s, deaths=%s, assists=%s' % (
rec.stats.kills, rec.stats.deaths, rec.stats.assists))
print(' victorious: %s' % rec.victory)
print(' date: %d-%02d-%02d' % (rec.date.year, rec.date.month, rec.date.day))
# sample usage
player = 'Fizz'
print('\n%s had %s kills in the game' % (player, info2[player].stats.kills))
输出:
info2:
player 'Shyvana':
stats: kills=12, deaths=4, assists=5
victorious: False
date: 2012-11-22
player 'Miss Fortune':
stats: kills=12, deaths=4, assists=3
victorious: True
date: 2012-11-22
player 'Fizz':
stats: kills=12, deaths=4, assists=5
victorious: True
date: 2012-11-22
Fizz had 12 kills in the game
答案 1 :(得分:3)
有两种方法可以从文本文件示例中读取数据。
第一种方法
您可以使用python的csv模块并指定您的分隔符为-
。
请参阅http://www.doughellmann.com/PyMOTW/csv/
第二种方法
或者,如果您不想使用此csv模块,则可以在将文件中的每一行读取为字符串后,使用split
方法。
f = open('myTextFile.txt', "r")
lines = f.readlines()
for line in lines:
words = line.split("-") # words is a list (of strings from a line), delimited by "-".
因此,在上面的示例中,champname
实际上是words
列表中的第一项,即words[0]
。
答案 2 :(得分:3)
你想使用split(' - ')获取部分,然后再次获取数字:
for line in yourfile.readlines ():
data = line.split (' - ')
nums = [int (x) for x in data[1].split ('/')]
应该在data []和nums []中获取所需的所有内容。或者,您可以使用re模块并为其编写正则表达式。但这似乎不够复杂。
答案 3 :(得分:3)
# Iterates over the lines in the file.
for line in open('data_file.txt'):
# Splits the line in four elements separated by dashes. Each element is then
# unpacked to the correct variable name.
champname, score, winloss, timestamp = line.split(' - ')
# Since 'score' holds the string with the three values joined,
# we need to split them again, this time using a slash as separator.
# This results in a list of strings, so we apply the 'int' function
# to each of them to convert to integer. This list of integers is
# then unpacked into the kills, deaths and assists variables
kills, deaths, assists = map(int, score.split('/'))
# Now you are you free to use the variables read to whatever you want. Since
# kills, deaths and assists are integers, you can sum, multiply and add
# them easily.
答案 4 :(得分:1)
首先,您将该行分成数据片段
>>> name, score, result, date = "Fizz - 12/4/5 - Win - 2012-11-22".split(' - ')
>>> name
'Fizz'
>>> score
'12/4/5'
>>> result
'Win'
>>> date
'2012-11-22'
其次,解析你的分数
>>> k,d,a = map(int, score.split('/'))
>>> k,d,a
(12, 4, 5)
最后,将日期字符串转换为日期对象
>>> from datetime import datetime
>>> datetime.strptime(date, '%Y-%M-%d').date()
datetime.date(2012, 1, 22)
现在,您已解析所有部件并将其规范化为数据类型。