在调用不同文件的函数中,以某个字符结尾的单词有多少个?

pup*_*kik 3 python

因此,我正在尝试制作一个小的函数,该函数以文件名作为参数并返回文件中以“!”,“?”结尾的单词数。要么 ”。”。

到目前为止,我已经尝试了以下方法:

def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count
Run Code Online (Sandbox Code Playgroud)

但这不起作用,也不计算在单独的调用文件中有多少个以这些指定字符结尾的单词。我曾想过拆分每个单词并循环遍历每个字符,如果它包含一个字符,它将为计数增加+1,但是我不确定该怎么做。

编辑:还想到只使用.count吗?那行得通吗?干杯

edit2:这是我要通过的doctest:

def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """
Run Code Online (Sandbox Code Playgroud)

这是失败的.txt的链接:https : //pastebin.com/raw/1NYPeY29

这是说期望值:45分:52

Rak*_*esh 5

使用:

def count_possible_sentences(file_name):
    count = 0
    with open(file_name) as wordfile:              #Open file for read
        for line in wordfile:                      #Iterate each line
            for word in line.strip().split():      #Get words
                if word.endswith(("!", "?", ".")):  #Check if word ends with
                    count += 1
    return count
Run Code Online (Sandbox Code Playgroud)