You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用endswith统计txt文件中以'er'结尾单词数量的问题排查

代码问题排查与修复

核心错误:全局变量作用域问题

你在函数外部定义的wordcount属于全局变量,Python默认不允许函数内部直接修改全局变量,不加声明就执行wordcount += 1时,Python会将wordcount判定为未定义的局部变量,直接抛出UnboundLocalError,无法得到正确统计结果。

逻辑适配说明

split()方法会按空格分割文本,带标点的er结尾单词(如danser,、er.)不会被endswith("er")匹配,刚好符合题目「忽略末尾带标点的er结尾场景」的要求,无需额外处理标点。

修复方案1 (保留原函数结构,声明全局变量)

file = open("in1140-tekst.txt", encoding="utf-8")
data = file.read()
file.close()
wordcount = 0
def count_words(string):
    global wordcount # 声明此处使用全局变量
    for word in string.split():
        if word.endswith("er"):
            wordcount += 1
count_words(data)
print(wordcount)

修复方案2 (更推荐,避免全局变量污染)

直接让函数返回统计结果,不需要维护全局变量,逻辑更清晰:

def count_words(string):
    wordcount = 0
    for word in string.split():
        if word.endswith("er"):
            wordcount += 1
    return wordcount

# 用with上下文管理器自动处理文件开闭,无需手动调用close()
with open("in1140-tekst.txt", encoding="utf-8") as file:
    data = file.read()

print(count_words(data))

内容的提问来源于stack exchange,提问作者python noob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:54:04