2014-04-28 4 views
-1

지금 몇 주 동안 프로젝트를 진행했으며 최종 기한이 끝났습니다. 하나에서 설정 한 모든 작업을 완료했습니다. 내 자신에 적어도 몇 주 동안 그것을해라. 그러나 나는 somone가 나를 도울 수 있었던 지 그렇게 단지 그것을 wroking 할 수있다. 나는 정말로 그것을 apreciate 할 것이다. 작업은 생성 된 데이터를 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 

Im은 잘 작동하지 않으며, 파이썬 3.3.2에서 작동하도록 도와 줄 수 있다면 정말 고맙겠습니다. 마감일은 내일이고 올바르게 처리하지 않으면 나쁜 결과가 발생할 것이기 때문에, 그것의 다만 나가 지금 당분간 그것을 독자적으로 파악하는 것을 시도하고있다 그리고 누군가가 그것에게 일을 얻을 수 있던 경우에 나가 남겨둔 어떤 시간도 없으면 나는 진짜로 그것을 평가할 것입니다, 감사합니다 순전히 fo r 도움.

+0

이 당신이 당신의 GCSEs에 부정 행위를 도와주는 사이트가 아닙니다. – jonrsharpe

+1

가능한 [파이썬 3.3.2의 Txt로 저장하는 문제] (http://stackoverflow.com/questions/23137383/issue-with-saving-into-a-txt-in-python-3-3- 2) – jonrsharpe

답변

0

파이썬이 char1의 두 번째 문자를 변경하려고한다고 생각합니다. - 할 수없는 것입니다. char1이 이미 첫 번째 문자의 이름이므로 라인을 참조하십시오. 3 파일.

char1을 실제로 문자 1에 대한 데이터로 만들려는 코드에서 asume을 선택합니다. 그렇다면 사전을 사용하여 데이터를 저장하려는 경우 - 이름과 강도에 키를 사용할 수 있습니다. , 그리고 캐릭터의 기술 - 그건 일을 매우 비옥 한 방법입니다.

사전을 사용하는 경우에도 루프를 변경해야합니다.

참고 :이 작업을 수행하는 더 좋은 방법은 문자 클래스를 사용하는 것입니다. 이는 문자에 대한 모든 데이터를 보유하고 특수화 된 출력 방법을가집니다.하지만 지금은 생각보다 훨씬 뛰어납니다.

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() 
관련 문제