2016-10-02 22 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が必要で、正規表現を使用します。

大文字と小文字を区別したい場合(例:「あなたとあなた」)、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") 
関連する問題