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

Python如何读取文件并批量修改指定词汇相邻内容?

求助:批量修改文件中特定词汇相邻的内容

我一开始尝试定位ifrs_Revenue并修改它旁边的内容,但代码未生效:

f = open(input_path +'/CIS' + "/16_1분기보고서_03_포괄손익계산서_연결_2212.txt")
while line: 
    if "ifrs_Revenue" in line:
        s_line = line.split("\t") 
        idx = s_line.index("ifrs_Revenue") 
        value = s_line[idx+1] 
        value = value.replace(value,'매출액') 
        break    
    line = f.readline()

之后我换了一种批量替换特定词汇的方法,代码如下:

def inplace_change(filename, old_string, new_string):
   
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    
    with open(filename, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

b_list = os.listdir(input_path +'/CIS')
for blist in b_list:
    for old, new in zip(['   지배기업의 소유주에게 귀속되는 당기순이익(손실)','수익(매출액)', '영업수익', '영업이익(손실)', '관리비및판매비', '영업관리비용(수익)','   지배기업의 소유주지분'   ],['당기순이익(지배)', '매출액', '매출액','영업이익', '판매비와관리비', '판매비와관리비','당기순이익(지배)'   ]):
        inplace_change(input_path +'/CIS'+ '/' + blist,  old_string= old, new_string= new)  
        break

我的核心需求是找到特定词汇后,修改它相邻位置的内容,但试了两种方法都没达到预期效果。补充说明:目标文件是制表符分隔的文本,比如某一行中ifrs_Revenue是其中一个元素,我需要把它右侧的元素替换为指定内容;同时还有多组类似的词汇需要批量处理相邻内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:18:27