2017-11-30 1 views
1

그래서 필자가 작성한 프로그램의 결합 된 인스턴스 (숫자 목록)가 들어있는 파일이 있습니다. 그런 다음 교육 및 테스트 파일에 '@'이있는 모든 줄을 입력합니다. 이제는 28,709 개의 인스턴스를 교육용 파일에 저장하고 나머지 파일 인스턴스는 테스트 파일에 저장하려고합니다. 이 코드 두 개의 다른 파일에 파일 섹션 작성하기

내가 이렇게

:
import itertools 

# Splits the training and testing instances 
# with the newly reduced attributes 

training = open('training.txt', 'w') 
testing = open('testing.txt', 'w') 

linecount = 0 

with open('combined.txt', 'r') as f: 
    for l in f: 
     if not l.startswith('@'): 
      break 
     else: 
      training.write(l) 
      testing.write(l) 
      linecount += 1 

with open('combined.txt', 'r') as f: 
    newcount = 0 
    for l in f: 
     while(newcount < linecount): 
      f.next() 
      newcount += 1 

     if linecount > (linecount + 28709): 
      testing.write(l) 
     else: 
      training.write(l) 
     linecount += 1 
    '''# Write 28,709 instances to training set 
    for l in itertools.islice(f, linecount, linecount + 28709): 
     training.write(l) 
    # Write rest of instances to testing set 
    for i in xrange(linecount + 28710): 
     f.next() 
    for l in f: 
     testing.write(l)''' 

.. 그것은 훈련 세트에 모든 인스턴스를하고 아무것도 출력이 설정 테스팅을하지 않습니다하지 않습니다. 원래 결합 파일을 여기에서 찾을 수 있습니다 (너무 큰 여기에 붙여 넣) : https://gist.githubusercontent.com/ryankshah/618fde939a54c5eb8642135ab1f4514c/raw/a5a11c0fc301a6724b9af4c413d76b96ffa9859c/combined.txt

편집 : 모든 @ 기호 라인 모두에 있어야합니다. 그런 다음 마지막 '@'뒤의 첫 번째 28709 줄이 테스트 파일에 있고 나머지는 테스트 파일에 있어야합니다.

감사합니다!

+0

테스트 및 교육 파일에 정확히 무엇이 있어야하는지 혼란 스럽습니다. 모든 @ 기호 행은 모두에 있어야합니다. 그런 다음 @ 기호가없는 줄을 테스트 파일에 넣으시겠습니까? –

+0

@AlexF 모든 @ 기호 행은 모두에 있어야합니다. 그런 다음 마지막 '@'다음의 첫 번째 28709 줄이 테스트 파일에 있어야하고 나머지는 테스트 파일에 있어야합니다 – rshah

답변

1

필요한 것을 제공해야합니다. 코드에서 변경된 내용을 설명하기 위해 주석을 추가했습니다.

# Splits the training and testing instances 
# with the newly reduced attributes 

training = open('training.txt', 'w') 
testing = open('testing.txt', 'w') 

linecount = 0 

with open('combined.txt', 'r') as f: 
    for l in f: 
     if not l.startswith('@'): 
      break 
     else: 
      training.write(l) 
      testing.write(l) 
     # increment every time to get position of last '@' symbol 
     # can't skip lines in between '@'' symbols 
     linecount += 1 

val = 28709 

with open('combined.txt', 'r') as f: 
    # skip first n lines up to last '@' symbol 
    for _ in range(linecount): 
     f.next() 

    # write first 28709 lines after last '@' symbol to training file 
    new_linecount = 0 
    for l in f: 
     if new_linecount >= val: 
      testing.write(l) 
     else: 
      training.write(l) 
     new_linecount += 1 
    '''# Write 28,709 instances to training set 
    for l in itertools.islice(f, linecount, linecount + 28709): 
     training.write(l) 
    # Write rest of instances to testing set 
    for i in xrange(linecount + 28710): 
     f.next() 
    for l in f: 
     testing.write(l)'''