2014-01-18 7 views
0

"여우는 게으른 개로 점프합니다"라는 문장이 있으며이 문장에서 각 단어가 나오는 횟수를 계산했습니다. 출력은 다음과 같이해야합니다 :한 줄에 한 문장으로 단어의 빈도를 인쇄하십시오.

brown:1,dog:1,fox:1,jumps:1,lazy:1,over:1,quick:1,the:2 

이 출력의 문자 사이에 공백이 없어야하고, 단어/숫자 사이에 쉼표가 있어야한다. 내 프로그램의 출력은 다음과 같습니다

,brown:1,dog:1,fox:1,jumps:1,lazy:1,over:1,quick:1,the:2 

나는 '갈색'앞에 쉼표 장소가 있다는 것을 찾을 수 있습니다. 이것을 인쇄하는 더 쉬운 방법이 있습니까?

filename = os.path.basename(path) 


    with open(filename, 'r+') as f: 
     fline = f.read()  
     fwords = fline.split() 

     allwords = [word.lower() for word in fwords] 
     sortwords = list(set(allwords)) 


    r = sorted(sortwords, key=str.lower) 

    finalwords = ','.join(r) 

    sys.stdout.write(str(finalwords)) 
    print '\n' 

    countlist = {} 
    for word in allwords: 
     try: countlist[word] += 1 
     except KeyError: countlist[word] = 1  

    for c,num in sorted(countlist.items()): 
     sys.stdout.write(",{:}:{:}".format(c, num)) 

답변

1

단어 목록을 만드는 몇 가지 다른 방법. 첫째, 한 줄짜리 :

DSM에서 지적했듯이이 방법은 긴 목록에서는 느려질 수 있습니다. 출력의 경우

from itertools import defaultdict 
countlist = defaultdict(int) 
for word in allwords: 
    countlist[word] += 1 

시작 부분에 하나를 가진 피하는 ,, 개별 단어 수를 가입 : 대체는 defaultdict을 사용하는 것입니다 영업 이익이 이미 사전을 가지고

sys.stdout.write(",".join(["{:}:{:}".format(key, value) for key, value in countlist .items()])) 
+0

counts -'countlist'는 혼동을 일으키는 이름입니다. 그리고 OP의 계산 방법은 선형이므로 많은 단어에 대해서'.count'보다 빠릅니다. – DSM

+0

@DSM, OP에 단어 수가 포함 된 사전이 있다는 것을 알고 있습니다. 이것은 대안이며, 가능하면 더 쉬울 수도 있지만 (아주 긴리스트에서는 느리지 만 느린 것입니다.) 방법입니다. 나는'defaultdict'를 사용하는 예제를 추가 할 것입니다. – mhlester

관련 문제