计算文本文件中以删节号结尾的句子数

时间:2018-11-16 17:56:50

标签: python python-3.x

我正在尝试创建一个计算文本文件中句子数的函数。在这种情况下,句子是指任何以“。”,“?”或“!”结尾的字符串。

我是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'))

2 个答案:

答案 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,这将会起作用。
我认为,执行此操作的最佳方法是使用

而不是使用find(返回数字而不是布尔值)来查找

if sentence in endofSentence:  
    numberOfSentences+=1