用Python解析输入文件

2024-06-08 22:03:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个纯文本文件,其中包含一些数据,我正试图使用Python(3.2版)程序打开和读取该文件,并试图将该数据加载到程序中的数据结构中。

下面是我的文本文件(文件名为“data.txt”)

NAME: Joe Smith
CLASS: Fighter
STR: 14
DEX: 7

我的程序是这样的:

player_name = None
player_class = None
player_STR = None
player_DEX = None
f = open("data.txt")
data = f.readlines()
for d in data:
    # parse input, assign values to variables
    print(d)
f.close()

我的问题是,如何给变量赋值(比如在程序中设置player_STR=14)?


Tags: 文件数据name程序txtnone数据结构data
3条回答
player = {}
f = open("data.txt")
data = f.readlines()
for line in data:
    # parse input, assign values to variables
    key, value = line.split(":")
    player[key.strip()] = value.strip()
f.close()

现在,播放器的名称将是player['name'],文件中所有其他属性的名称也将是player['name']

最直接的方法是一次分配一个变量:

f = open("data.txt")              
for line in f:                       # loop over the file directly
    line = line.rstrip()             # remove the trailing newline
    if line.startswith('NAME: '):
        player_name = line[6:]
    elif line.startswith('CLASS: '):
        player_class = line[7:]
    elif line.startswith('STR: '):
        player_strength = int(line[5:])
    elif line.startswith('DEX: '):
        player_dexterity = int(line[5:])
    else:
        raise ValueError('Unknown attribute: %r' % line)
f.close()

也就是说,大多数Python程序员将值存储在字典中,而不是变量中。字段可以被剥离(删除行尾)并用characteristic, value = data.rstrip().split(':')分割。如果该值应为数字而不是字符串,请使用float()int()转换它。

import re

pattern = re.compile(r'([\w]+): ([\w\s]+)')

f = open("data.txt")
v = dict(pattern.findall(f.read()))
player_name = v.get("name")
plater_class = v.get('class')
# ...


f.close()

相关问题 更多 >