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

替换文本缩写时遇TypeError:fix()缺少必需位置参数's'求助

解决Python contractions.fix() 报TypeError的问题

问题描述

我写了一段Python代码,用来把文本文件里的单词缩写(比如didn't)替换成完整形式(比如did not),代码如下:

import os
import contractions
directory = 'C:\\Users\\User\\Desktop\\test1'
os.chdir('C:\\Users\\User\\Desktop\\test1')
for filename in os.listdir(directory):
    if filename.endswith(".txt"):
        f = open(filename, 'r')
        text = f.read()
        lines = [contractions.fix() for line in filename]
        with open(filename, 'w') as out:
            out.writelines(lines)

运行时出现了错误:

Traceback (most recent call last):
...
TypeError: fix() missing 1 required positional argument: 's'

请求帮忙解决这个问题。


问题分析与解决方案

嘿,这个错误其实很好排查——你调用contractions.fix()的时候没传要处理的文本参数!而且代码里还有几个小细节需要调整,我一起帮你修正:

1. 核心错误:contractions.fix()缺少必要参数

contractions.fix()方法必须接收一个字符串参数(也就是你要处理的文本内容),你现在写的contractions.fix()是空调用,自然会抛出TypeError提示缺少参数。

2. 其他待修正的问题

  • 你遍历的是filename(文件名)而不是读取到的文本行,这完全偏离了目标,应该遍历读取到的文本内容或者直接处理整个文本。
  • 直接用open()而不搭配with语句,可能会导致文件句柄泄漏,建议统一用with来管理文件操作,更安全。
  • Windows路径里的反斜杠最好用双反斜杠\\或者原始字符串r'路径',避免转义字符引发的问题。

修正后的完整代码

import os
import contractions

# 使用原始字符串避免路径转义问题
directory = r'C:\Users\User\Desktop\test1'
os.chdir(directory)

for filename in os.listdir(directory):
    if filename.endswith(".txt"):
        # 用with语句安全读取文件内容
        with open(filename, 'r', encoding='utf-8') as f:
            text = f.read()
        
        # 处理整个文本里的缩写
        fixed_text = contractions.fix(text)
        
        # 写入处理后的内容
        with open(filename, 'w', encoding='utf-8') as out:
            out.write(fixed_text)

大文件优化方案(逐行处理)

如果你的文本文件很大,担心一次性读取占内存,可以改成逐行处理的版本:

import os
import contractions

directory = r'C:\Users\User\Desktop\test1'
os.chdir(directory)

for filename in os.listdir(directory):
    if filename.endswith(".txt"):
        fixed_lines = []
        with open(filename, 'r', encoding='utf-8') as f:
            for line in f:
                # 逐行处理缩写
                fixed_line = contractions.fix(line)
                fixed_lines.append(fixed_line)
        
        with open(filename, 'w', encoding='utf-8') as out:
            out.writelines(fixed_lines)

这样修改后,代码就能正确识别并替换文本里的缩写,也不会再报那个TypeError了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:19:55