gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:30:01 25 4
gpt4 key购买 nike

所以我正在尝试制作一个小函数,它将文件名作为参数并返回文件中有多少个以“!”,“?”结尾的单词或“.”。

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

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

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

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

编辑2:这是我试图让它们通过的 doctests:

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
"""

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

它说预期:45 得到:52

最佳答案

使用:

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

关于python - 在调用不同文件的函数中有多少个单词以某个字符结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56356785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com