2017-10-15 69 views
-1

如果字與用戶輸入完全相同,如何使用布爾值對文件中的字進行計數?如何計算文件中區分大小寫的獨立字

因此,如果case sensitive == True它只會計數,如果案件匹配。這個詞也不能成爲另一個詞的一部分。

例如:如果input = Apple該代碼將只計算單詞AppleApple+Apple-。但它不會計算單詞appleapplepie或​​。

我做了一個模板來說明我的意思:

# open the file 
    f = open("months.txt") 

    # ask for word to search 
    word = input("What word do you want to search (Note: Case Sensitive): ") 

    # read each line in the file 
    for month in f.readlines(): 

    # <Code to only count case sensitive, independent words, in file "months.exe". (Boolean)> 
    # <Code to print number of how many times the word appears> 

    f.close() 
+1

如果我沒有誤解,那麼你可以使用'str.count(substring)'方法來查找'str'中'substring'的出現次數 - 這是區分大小寫的IIRC –

+0

我不明白不幸的是,這裏有什麼在字符串中查找子字符串「不區分大小寫」很容易,但是判斷一個由空格包圍的字符是否是一個單詞可能有點棘手。 – ForceBru

+0

對不起,我的錯誤解釋是,我並沒有完全理解我的教授想要的。 – user8779857

回答

1

您可以使用re.findall()和用戶輸入格式化成模式:

import re 

word = ... 
with open("months.txt") as f: 
    count = sum(len(re.findall(r'\b{}\b'.format(word), line)) for line in f) 

\b標誌着一個字邊界正則表達式:

>>> word = 'Apple' 
>>> len(re.findall(r'\b{}\b'.format(word), "Apple. or Apple? or +Apple- Applepie")) 
3 
+0

它應該匹配用戶輸入。所以,你應該把它包裝到一個方法中,在那裏你傳遞一個詞來計算。 –

+1

@ E.Z。誠然,這可能也是一個問題。更新... – schwobaseggl

+0

這正是我正在尋找的。 – user8779857