出现AttributeError错误:'str'对象无'text'属性,求代码问题排查
排查AttributeError: 'str' object has no attribute 'text'错误
这个错误的原因很直接——你代码里的data1是通过myfile.read()读取到的字符串对象,而字符串本身根本没有.text属性,你却反复调用data1.text,这就触发了这个AttributeError。
具体问题行分析
看你这段出错的代码:
auto = data1.text[data1.text.find(searchKey) + len(searchKey): data1.text.find(searchEndKey, data1.text.find(searchKey) + len(searchKey) + 1)]
这里所有的data1.text都是多余的,因为data1已经是文件读取出来的文本内容了,直接用data1就行。
修正后的完整代码
我帮你把错误修正,同时补全了你没写完的替换代码:
import requests import time # 读取文件内容,data1本身就是字符串,无需.text with open("C:\\temp\\cars.txt", 'r') as myfile: data1 = myfile.read() searchKey = "ford=" searchEndKey = '"' # 计算截取的起始和结束索引,直接操作data1 start_idx = data1.find(searchKey) + len(searchKey) end_idx = data1.find(searchEndKey, start_idx + 1) auto = data1[start_idx: end_idx] # 处理文件内容替换 with open("C:\\temp\\cars2.txt", "rt") as fin: with open("C:\\temp\\cars3.txt", "wt") as fout: for line in fin: # 将'ford='替换为'ford='加上截取到的auto值 fout.write(line.replace('ford=', f'ford={auto}'))
额外优化建议
为了避免因为searchKey或searchEndKey不存在导致的索引错误,建议加上存在性判断:
start_idx = data1.find(searchKey) if start_idx == -1: print("未找到关键词 'ford='") auto = "" else: start_idx += len(searchKey) end_idx = data1.find(searchEndKey, start_idx + 1) if end_idx == -1: print("未找到匹配的结束引号") auto = data1[start_idx:] # 如果没找到结束符,就截取到文本末尾 else: auto = data1[start_idx: end_idx]
内容的提问来源于stack exchange,提问作者matrixebiz
相关产品推荐
相关产品推荐

