我正在尝试创建一个计算文本文件中句子数的函数。在这种情况下,句子是指任何以“。”,“?”或“!”结尾的字符串。
我是Python的新手,我在弄清楚如何做到这一点时遇到了麻烦。我不断收到错误消息“ UnboundLocalError:分配前引用了局部变量'numberofSentences'”。任何帮助将不胜感激!
def countSentences(filename):
endofSentence =['.', '!', '?']
for sentence in filename:
for fullStops in endofSentence:
if numberofSentences.find(fullStops) == true:
numberofSentences = numberofSentences+1
return numberofSentences
print(countSentences('paragraph.txt'))
答案 0 :(得分:0)
您需要先将变量初始化为某种值,然后再递增。您还需要打开文件本身,阅读它是文本并进行评估-不计算给定filename
中的字母。
# create file
with open("paragraph.txt","w") as f:
f.write("""
Some text. More text. Even
more text? No, dont need more of that!
Nevermore.""")
def countSentences(filename):
"""Count the number of !.? in a file. Return it."""
numberofSentences = 0 # init variable here before using it
with open(filename) as f: # read file
for line in f: # process line wise , each line char wise
for char in line:
if char in {'.', '!', '?'}:
numberofSentences += 1
return numberofSentences
print(countSentences('paragraph.txt'))
输出:
5
Doku:
答案 1 :(得分:0)
如果您首先检查了fullStop是否在句子中,并且您事先声明了numberOfSentences
,这将会起作用。
我认为,执行此操作的最佳方法是使用
if sentence in endofSentence:
numberOfSentences+=1