0

我有一个包含一些数据的纯文本文件,我正在尝试使用 Python(ver 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)?

4

3 回答 3

2
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()

now the name of your player will be player['name'], and the same goes for all other properties in your file.

于 2012-12-15T16:11:35.160 回答
1
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()
于 2012-12-15T16:12:44.023 回答
0

The most direct way to do it is to assign the variables one at a time:

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()

That said, most Python programmers would stored the values in a dictionary rather than in variables. The fields can be stripped (removing the line endings) and split with: characteristic, value = data.rstrip().split(':'). If the value should be a number instead of a string, convert it with float() or int().

于 2012-12-15T16:13:40.730 回答