2013-11-04 1 views
0

과제 중 하나에 문제가 있습니다.텍스트 파일에서 컴 파운 션 기호 계산하기

나는 텍스트 파일을 가져 와서 그 안에 들어있는 컴 파운 션 심볼을 계산 했으므로 코드를 작성해야했다. 그런 다음

c1 = Counter('hello there') 

:

from collections import Counter 

chars = ['==', '>=', '<=', '<', '>'] 
file = open(input('specify a file')) 
character_distr = Counter() 

for line in file: 
    character_distr += Counter(line.lower()) 

print('Distribution of characters: ') 
for char, count in sorted(character_distr.items()): 
    if char in chars: 
    print('{} : {}'.format(char, count)) 

답변

1

이 시도 :

문제는 늘 인쇄 '==', '> ='또는 '< ='

내 코드가 있다는 것입니다 이것을 시도하십시오 :

c2 = Counter('hello there'.split()) 

N 그 차이는 무엇입니까? Counter에 문자열이 입력되면 문자는입니다. 개별 문자 이외의 토큰을 계산하려면 문자열을 에 split으로 입력해야합니다.

연산자 사이에 공백이 있으면 .split()line.lower()에 추가하면됩니다. 거기에 (물론, 합법적 인 경우), 당신은 좀 더 정교한 렉서 또는 (더 가능성이) 정규 표현식이 필요합니다.

import re 
expression = 'if x>4: do_thing(); elif x==12: other_thing = x' 

len(re.findall(r'==|>=|<=|<|>',expression)) 
Out[12]: 2 
+0

감사합니다. – mix

관련 문제