如何将结果保存为.txt文件
我已经做了一个项目几周了,明天就是最后的截止日期。我完成了所有的任务,除了一个。我自己尝试了几周,但就是搞不定。如果有人能帮我,我会非常感激。这个任务是创建一个程序,把生成的数据保存到一个txt文件里,这是我目前的代码:
import random
char1=str(input('Please enter a name for character 1: '))
strh1=((random.randrange(1,4))//(random.randrange(1,12))+10)
skl1=((random.randrange(1,4))//(random.randrange(1,12))+10)
print ('%s has a strength value of %s and a skill value of %s)'%(char1,strh1,skl1))
char2=str(input('Please enter a name for character 2: '))
strh2=((random.randrange(1,4))//(random.randrange(1,12))+10)
skl2=((random.randrange(1,4))//(random.randrange(1,12))+10)
print('%s has a strength value of %s and a skill value of %s'%(char1,strh1,skl1))
char1[1]="Strength now {} ".format(strh1)
char1[2]="Skill now {} ".format(skl1)
char2[1]="Strength now {} ".format(strh2)
print()
char2[2]="Skill now {}".format(skl2)
print()
myFile=open('CharAttValues.txt','wt')
for i in Char1:
myFile.write (i)
myFile.write ('\n')
for i in Char2:
myFile.write (i)
myFile.write('\n')
myFile.close()
现在我想让这个程序写入txt文件,但在程序结束时保存数据时总是出错:
Traceback (most recent call last):
File "E:\CA2 solution.py", line 14, in <module>
char1[1]="Strength now {} ".format(strh1)
TypeError: 'str' object does not support item assignment
我不太确定怎么才能让它工作,如果有人能帮我在python 3.3.2中解决这个问题,我会非常感激,因为我的截止日期是明天,如果没有正确提交会有很糟糕的后果。我已经尝试了很久,但时间不多了,所以如果有人能帮我解决这个问题,我会非常感激,非常感谢任何帮助。
2 个回答
0
Python认为你想要改变char1的第二个字符,但其实这是做不到的。而且我不太确定你是否真的想这么做,因为char1已经是你第一个角色的名字了,看看你文件的第3行就知道了。
从你的代码来看,我猜你是想让char1真正代表角色1的数据。如果是这样的话,或许你可以用字典来保存这些数据。这样你就可以用键来表示角色的名字、力量和技能,这是一种非常符合Python风格的做法。
如果你使用字典的话,你也需要修改你的循环。
另外:更好的做法是创建一个角色类,这样可以把角色的所有数据都放在一起,并且有一个专门的方法来输出这些数据。不过我觉得现在对你来说这可能有点复杂。
0
这里有一个比较大的改动;如果你仔细看看,你应该能学到很多东西 ;-)
首先,我觉得你写的随机强度代码有点难懂——它到底会产生什么样的值并不清楚——所以我写了一个辅助函数:
from bisect import bisect_left
import random
def make_rand_distr(value_odds):
"""
Create a discrete random-value generator
according to a specified distribution
Input:
value_odds: {x_value: odds_of_x, y_value: odds_of_y, ...}
Output:
function which, when called, returns one of
(x_value or y_value or ...) distributed
according to the given odds
"""
# calculate the cumulative distribution
total = 0.
cum_prob = []
values = []
for value,odds in value_odds.items():
total += odds
cum_prob.append(total)
values.append(value)
# create a new function
def rand_distr():
# generate a uniformly-distributed random number
rnd = random.random() * total
# use that to index into the cumulative distribution
index = bisect_left(cum_prob, rnd)
# then return the associated value
return values[index]
# return the new function
return rand_distr
然后我用这个函数来创建更明确的强度和技能函数(最终的值分布和你原来的代码是一样的):
# When you call rand_strength(), you will get
# Value Odds
# 10 27/33
# 11 4/33
# 12 1/33
# 13 1/33
rand_strength = make_rand_distr({10: 27, 11: 4, 12: 1, 13: 1})
rand_skill = make_rand_distr({10: 27, 11: 4, 12: 1, 13: 1})
(注意,这样你可以轻松创建任意的分布,这些分布不一定对应于任何明显的函数);
接着,我写了一个角色类:
class Character:
def __init__(self, ch):
self.name = input(
"Please enter a name for character {}: "
.format(ch)
).strip()
self.strength = rand_strength()
self.skill = rand_skill()
def __str__(self):
return (
"{} has strength={} and skill={}"
.format(self.name, self.strength, self.skill)
)
def __repr__(self):
return (
"{name}:\n"
" Strength now {strength}\n"
" Skill now {skill}\n"
.format(
name = self.name,
strength = self.strength,
skill = self.skill
)
)
然后这样使用它:
NUM_CHARS = 2
OUT_FILE = "char_attr_values.txt"
def main():
# create characters
chars = [Character(ch) for ch in range(1, NUM_CHARS+1)]
# display character stats
for char in chars:
print(char) # calls char.__str__ implicitly
# save character data to output file
with open(OUT_FILE, "w") as outf:
for char in chars:
outf.write(repr(char)) # delegates to char.__repr__
if __name__=="__main__":
main()