2014-02-10 3 views
0

당신의 도움이 필요합니다. 필자는 파일의 특정 줄을 다른 두 줄로 컴파일하려고합니다. 변수 n과 p는 전역 변수입니다. 그들은 동일한 것으로 가정된다 -끝에 파일이 비어 있습니다. 파이썬

대문자 X와 소문자 x가 작은 관찰,
def files(): 
    i = 1 
    X = 1 
    f90 = open('C:\Users\Homura\Desktop\python\data90.txt' , 'w') 
    f10 = open('C:\Users\Homura\Desktop\python\data10.txt' , 'w') 
    f = open('C:\Users\Homura\Desktop\python\TData.txt' , 'r') 
    while True: 
     line = f.readline() 
     if line.startswith('0'): 
      while i <= n: # taking 90% of negative tweets and writing them in f90 
       f90.write(line) 
       i += 1 
      while i != n: #putting the rest of the negative tweets (10%) in the f10 file 
       f10.write(line) 
       i += 1 
     elif line.startswith('1'): 
      while (x <= p): # taking 90% of positive tweets and writing them in f90 
       f90.write(line) 
       x += 1 
      while (x != p): #putting the rest of the positive tweets (10%) in the f10 file 
       f10.write(line) 
       x += 1     

    f.close() 
    f10.close() 
    f90.close() 
    return f10 , f90 
+0

이 변경

f = open('C:\Users\Homura\Desktop\python\TData.txt' , 'r') 

봅니다, 당신이 뭘하려합니다, 당신은 프로그램이 무엇을 원하고, 당신은 "의 compy"무엇을 의미합니까? – Elisha

+1

s/wanrt/want s/compy/copy? – doctorlove

+0

파일에서 샘플 라인을 제안 할 수 있다면 더 많이 도와 드릴 수 있습니다. – GMPrazzoli

답변

1

첫째, 당신이 여기 내 코드?

다음으로, 시작하는 줄로 생각되는 문자로 시작하지 않을 가능성이 있습니다. 시작 부분에 0 또는 1을 붙잡기 위해 else를 추가하는 것이 좋습니다.

마지막으로 while True라고 말하기 때문에 while 루프가 종료되는 방법이 명확하지 않으므로 파일이 닫히지 않을 수 있습니다. ... 단지 파일의 줄을 일을 시도

이 시도 (예를 들어 here 참조) :

for line in f: 
     if line.startswith('0'): 
      while i <= n: # taking 90% of negative tweets and writing them in f90 
       f90.write(line) 
       i += 1 
      while i != n: #putting the rest of the negative tweets (10%) in the f10 file 
       f10.write(line) 
       i += 1 
     elif line.startswith('1'): 
      while (x <= p): # taking 90% of positive tweets and writing them in f90 
       f90.write(line) 
       x += 1 
      while (x != p): #putting the rest of the positive tweets (10%) in the f10 file 
       f10.write(line) 
       x += 1   
     else: 
      print "Unmatched line ", line 

편집

위의 모든 당신이를 열 관리하는 것으로 가정 입력 파일을 확인하십시오.

주 당신의 백 슬래시 입력 파일을 사용하는 docs

에서

" The backslash() character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences"

: 예를 들어, 원시 문자열 문제를 설명해주십시오

f = open(r'C:\Users\Homura\Desktop\python\TData.txt' , 'r') 
+0

도움을 주셔서 감사하지만 작동하지 않습니다. 파일 ". \ first.py", line 64 if line.startswith ('0') : ^ 들여 쓰기 오류 : 들여 쓰기 된 블록이 예상 됨 – kad

+0

들여 쓰기 오류는 종종 탭과 스페이스의 혼란이있다. – doctorlove

+0

필자가 줬던 것을 복사하고,이 문제가 있었지만, 들여 쓰기가 필요하지는 않지만, 파이썬은 더 잘 알고 있습니다. D – kad

관련 문제