Python 如何计算文件中区分大小写的独立词

Python 如何计算文件中区分大小写的独立词,python,python-3.x,Python,Python 3.x,如果文件中的单词与用户输入的单词完全相同,如何使用布尔值计算该单词 因此,如果区分大小写==True,则仅当大小写匹配时才会对其进行计数。这个词也不能是另一个词的一部分 例如:如果input=Apple代码将只计算单词Apple或Apple或+Apple-。但它不会计算单词apple或applepie或apple 我制作了一个模板来展示我的意思: # open the file f = open("months.txt") # ask for word to search wo

如果文件中的单词与用户输入的单词完全相同,如何使用布尔值计算该单词

因此,如果
区分大小写==True
,则仅当大小写匹配时才会对其进行计数。这个词也不能是另一个词的一部分

例如:如果
input=Apple
代码将只计算单词
Apple
Apple
+Apple-
。但它不会计算单词
apple
applepie
apple

我制作了一个模板来展示我的意思:

  # 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()
#打开文件
f=未结(“months.txt”)
#询问要搜索的单词
word=input(“要搜索的单词(注意:区分大小写):”)
#读取文件中的每一行
在f.readlines()中的月份:
#<仅统计文件“months.exe”中区分大小写的独立单词的代码。(布尔值)>
#<打印单词出现次数的代码>
f、 关闭()
您可以使用用户输入并将其格式化为模式:

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

如果我没有误解,那么您可以使用
str.count(substring)
方法来查找
substring
str
中出现的
substring
——这是区分大小写的IIRCI,不幸的是,这里什么都不懂。在字符串中查找“不区分大小写”的子字符串很容易,但确定由空格包围的字符块是否为单词可能有点棘手。很抱歉,我的解释不好,我也没有完全理解教授想要的内容。它应该与用户输入相匹配。所以,你应该把它包装成一个方法,在这个方法中,你传递一个要计数的单词。这正是我想要的。