2017-10-15 72 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