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

ATBS Mad Libs Python项目运行报AttributeError: str无read属性错误求助

错误原因

  • 你定义的NewFile变量始终存储的是input()返回的路径字符串,调用open()时没有将返回的文件对象赋值给任何变量,原有NewFile的值没有发生变化,因此调用.read()方法会报错。
  • 你使用a(追加)、w(写入)模式打开文件,这两种模式本身就不支持读取操作,要读取文件内容需要使用r(只读)模式。
  • 除此之外你的代码还存在多处逻辑错误:函数定义未声明参数、正则方法调用参数错误、遍历对象错误、字符串不可变导致替换不生效等。

修复后的完整代码

import os, re

file_path = input('Please enter the path of the file to be used:')
abs_path = os.path.abspath(file_path)
print(abs_path)

# 空文件运行本项目没有意义,不存在直接退出
if not os.path.exists(abs_path):
    print('Error: File does not exist.')
    exit()

# 读取文件内容,用with上下文自动管理文件句柄
with open(abs_path, 'r', encoding='utf-8') as f:
    content = f.read()

def replace_placeholders(raw_content):
    pattern = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB', re.I)
    # 找到所有占位符
    placeholders = pattern.findall(raw_content)
    for ph in placeholders:
        user_input = input(f'Enter an {ph.lower()}:\n')
        # 每次只替换1个匹配项,避免相同占位符一次性被全部替换成同一个值
        raw_content = pattern.sub(user_input, raw_content, count=1)
    return raw_content

final_content = replace_placeholders(content)
print(final_content)

new_file_name = 'new_source.txt'
with open(new_file_name, 'w', encoding='utf-8') as f:
    f.write(final_content)
print(f"The file is saved as '{new_file_name}'")

更简洁的实现思路

可以直接用re.sub的回调参数实现替换,无需手动遍历匹配项:

def replace_placeholders(raw_content):
    pattern = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB', re.I)
    def repl(match):
        ph = match.group()
        return input(f'Enter an {ph.lower()}:\n')
    return pattern.sub(repl, raw_content)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:06:03