如果字與用戶輸入完全相同,如何使用布爾值對文件中的字進行計數?如何計算文件中區分大小寫的獨立字
因此,如果case sensitive == True
它只會計數,如果案件匹配。這個詞也不能成爲另一個詞的一部分。
例如:如果input = Apple
該代碼將只計算單詞Apple
或Apple
或+Apple-
。但它不會計算單詞apple
或applepie
或。
我做了一個模板來說明我的意思:
# 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()
如果我沒有誤解,那麼你可以使用'str.count(substring)'方法來查找'str'中'substring'的出現次數 - 這是區分大小寫的IIRC –
我不明白不幸的是,這裏有什麼在字符串中查找子字符串「不區分大小寫」很容易,但是判斷一個由空格包圍的字符是否是一個單詞可能有點棘手。 – ForceBru
對不起,我的錯誤解釋是,我並沒有完全理解我的教授想要的。 – user8779857