如果字与用户输入完全相同,如何使用布尔值对文件中的字进行计数?如何计算文件中区分大小写的独立字
因此,如果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