2017-03-26 1 views
0

문제가 발생했습니다. (다가오는 시험에 대한 검토). 첫 번째 질문은 텍스트의 각 줄에있는 단어의 양을 출력 파일에 인쇄하도록 요청했습니다. 이것은 쉬운 일이었습니다. (내가 사용한 코드를 제공하지 않는다). 또 다른 비슷한 질문은 텍스트의 각 줄마다 고유 단어의 양 (개수)을 인쇄하는 것입니다. 내가 얻을 수 있었던 가장 먼 말은 단어를 목록에 추가하고 목록의 길이를 인쇄하는 것이었지만 각 반복을 추가하는 것으로 끝납니다. 그래서 그것은 7,14,21을 인쇄 할 것입니다. 7,7,7 대신 (exapain을 돕기위한 예제로)이 코드를 올바르게 작동하도록 수정하는 방법은 무엇입니까? 나는 지난 30 분 동안 노력 해왔다. 어떤 도움을 주시면 감사하겠습니다! 첫 번째 작품은 set을하려고하면Python 입출력 파일

def uniqueWords(inFile,outFile): 
    inf = open(inFile,'r') 
    outf = open(outFile,'w') 
    unique = [] 
    for line in inf: 
     wordlst = line.split() 
     for word in wordlst: 
      if word not in unique: 
       unique.append(word) 
     outf.write(str(len(unique))) 

    inf.close() 
    outf.close() 
uniqueWords('turn.txt','turnout.txt') 
+0

for 루프 내에서 "unique"을 정의하십시오. –

답변

2

: 각 라인의 독특한 단어의 수에 대한

def uniqueWords(inFile,outFile): 
    inf = open(inFile,'r') 
    outf = open(outFile,'w') 
    for line in inf: 
     wordlst = line.split() 
     count = len(wordlst) 
     outf.write(str(count)+'\n') 

    inf.close() 
    outf.close() 
uniqueWords('turn.txt','turnout.txt') 

코드 (실패) : 각 라인의 단어 수에 대한

코드

def uniqueWords(inFile,outFile): 
    inf = open(inFile,'r') 
    outf = open(outFile,'w') 
    for line in inf: 
     wordlst = line.split() 
     count = len(set(wordlst)) 
     outf.write(str(count)+'\n') 

    inf.close() 
    outf.close() 
uniqueWords('turn.txt','turnout.txt') 
+0

오 ..... 훨씬 쉬워졌습니다. 내가 LOL 할려고했던 것보다. 고마워요! –

+0

당신은 환영합니다 :) – zipa

+0

@RoryDaulton 헤즈 업에 감사드립니다. 아직 질문을 올리지는 않았지만 조언을 염두에 두십시오. – zipa