Int()转换在python中无法正常工作
因此,我正在制作一个python模块来为游戏中的角色创建和保存数据。 该类是Character,如下所示:Int()转换在python中无法正常工作,python,regex,class,python-2.5,Python,Regex,Class,Python 2.5,因此,我正在制作一个python模块来为游戏中的角色创建和保存数据。 该类是Character,如下所示: #!/usr/bin/python import os import re class Character: storage = None health = None strength = None xp = None def __init__(self,stg): os.chdir('/Users/alex/Desktop/Py
#!/usr/bin/python
import os
import re
class Character:
storage = None
health = None
strength = None
xp = None
def __init__(self,stg):
os.chdir('/Users/alex/Desktop/Python/Support/Character')
storage = stg
f = open(storage)
#health index = 0
#strength index = 1
#xp index = 2
string = f.read()
finder = re.compile('/n')
stats = finder.split(string)
health = int(stats[0])
strength = int(stats[1])
xp = int(stats[2])
f.close
def adjHealth(self,amount):
health += amount
def adjStrength(self,amount):
strength += amount
def adjXp(self,amount):
xp += amount
def save(self):
os.chdir('/Users/alex/Desktop/Python/Support/Character')
stats = [str(health),str(strength),str(xp)]
f = open(storage,'w')
f.writelines(stats)
每当我从python解释器执行此命令时:
>>> import character as ch
>>> ch.Character('jimmy')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/alex/Desktop/Python/Modules/character.py", line 22, in __init__
health = int(stats[0])
ValueError: invalid literal for int() with base 10: '10\n10\n0\n'
>>将字符导入为ch
>>>总角色(‘吉米’)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/Users/alex/Desktop/Python/Modules/character.py”,第22行,在__
health=int(统计信息[0])
ValueError:基数为10的int()的文本无效:“10\n10\n0\n”
它产生了这个错误。
它应该将f.read()
返回的字符串拆分为['10','10','0','']
对吗?那么为什么我不能将“10”转换成整数呢?
我对正则表达式有点陌生。这是正则表达式。下面将查找后跟
n
的文字字符/
:
finder = re.compile('/n')
另一方面,这将查找换行符:
finder = re.compile('\n')
f.read().splitlines()
问题出在您的正则表达式上,但是这里没有特别需要正则表达式-使用文件对象提供的功能,所有这些(更正)代码: 可以简化为一行:
stats = f.readlines()
或者,要使其不带尾随的换行符:
finder = re.compile('\n')
f.read().splitlines()
另外,请注意,您实际上并没有关闭文件-您需要调用close方法,而不仅仅是提及它。但最好的方法是使用和语句:
with open(stg) as f:
stats = f.readlines()
这样可以确保文件在处理完毕后立即关闭,即使在读取时出现问题
您的代码还存在另一个bug,它会很快而不是很晚攻击您:
health = int(stats[0])
创建一个名为health
的新函数局部变量-它不会将其分配给在类主体中设置为None
的函数。您可以通过分配给Character.health
来设置该值,但您几乎肯定需要self.health
。这将在adj*
方法中对您造成不利影响,这将在编写时导致错误
<>你也会从类体中删除这些变量——它们不象C++或java属性声明(Python不需要或者没有元魔法,甚至支持),以下两个字符串的含义完全不同:\n
和/n
。你能不能不这样做:stats=string.split('\n')
@Chris Oh。。。天哪,我现在觉得自己很愚蠢。谢谢谢谢,但是f.readlines()
函数返回列表中每个字符串末尾带有\n
字符的值。我必须去掉新行中的字符。但你在其他方面都是对的。非常感谢。@Awalrod在这种情况下,您仍然不需要regex-f.read().splitlines()
。