2016-10-02 3 views
0

안녕 얘들 아, 나는 얼마나 많은 시간 단어와 그의 수축을 (당신과 당신처럼) 계산하려고 노력하고있어. 문제는 제 말의 수축을 포착 할 방법이 보이지 않는다는 것입니다.

def paraula(file,palabrabuscar): 
    abrirLetra = open(file) #Open the file 
    palabras = "" 
    vegades = 0 
    for palabras in abrirLetra.read().split():#I split all words in text 
     if (palabras == palabrabuscar) :#Look for coincidence 
      vegades = vegades +1 

    abrirLetra.close() 
    return vegades 

file = 'lletra.txt' 
print paraula(file,"you") 
+0

내가 틀렸다면 용서해주세요. string.split()을 문자별로 나누지 않겠습니까? –

답변

0

아포스트로피, 공백 및 기타 구두점으로 파일을 분할 할 수 있습니다. 여러 분리 문자로 분리하려면 import re이 필요하고 정규 표현식을 사용해야합니다.

단어를 대문자와 일치 시키려면 (예 : '나와'YOU '), lower()을 사용해야합니다.

import re # use regular expressions 

def paraula(file,palabrabuscar): 
    abrirLetra = open(file) #Open the file 
    palabras = "" 
    vegades = 0 
    for palabras in re.split(r'[\s\'\"\.,;]+', abrirLetra.read()): 
     # split at every: \s whitespace 
     #     \' apostrophe 
     #     \" quotation mark 
     #     \. full stop 
     #     , comma 
     #     ; semi-colon 
     # 
     # The plus sign at the end splits at one or more delimiters in 
     # a row (for example "Hello. Hi." has a full stop and a space 
     # together between Hello and Hi). 
     # 
     # Backslashes are added before special characters 
     # (for example s matches the letter s, but \s matches whitespace). 

     if (palabras.lower() == palabrabuscar.lower()): #Look for coincidence 
      # Convert both to lowercase if you want to match 
      # you, You and YOU. 
      vegades = vegades +1 

    abrirLetra.close() 
    return vegades 

file = 'lletra.txt' 
print paraula(file,"you")