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

如何查找文本文件中两侧带空格的纯数字单词并替换为指定词汇

文本中独立纯数字单词的替换方案

要匹配并替换文本里两侧被空格分隔的纯数字单词(即独立的、完整的数字,而非嵌入其他字符串的数字),普通字符串替换无法处理长度不一的数字,需要用正则表达式实现精准匹配。

原代码存在的问题

你提供的代码有几个明显错误:

  • 重复打开同一文件,f.read()会将文件指针移到末尾,后续读取fin时无法获取内容
  • replace('', ' skaičius ')的替换目标为空字符串,完全不符合需求
  • 在循环内部调用close(),会导致第一次循环后文件就被关闭,后续循环直接报错
  • 未指定文件编码,容易出现乱码问题

正确实现方案

使用Python的re模块,通过正则表达式\b\d+\b匹配独立的纯数字单词:

  • \b:单词边界,确保匹配的是完整的独立单词,不会误替换类似abc123中的数字
  • \d+:匹配1个或多个数字,覆盖任意长度的纯数字单词

基础替换版本

import re

# 定义要替换成的指定词汇
target_word = "skaičius"

# 使用with语句自动管理文件,无需手动close
with open("tekstas.txt", "rt", encoding="utf-8") as input_file, \
     open("naujasTekstas.txt", "wt", encoding="utf-8") as output_file:
    for line in input_file:
        # 正则替换所有独立纯数字单词
        processed_line = re.sub(r'\b\d+\b', target_word, line)
        output_file.write(processed_line)

print("替换完成,结果已保存至naujasTekstas.txt")

包含"ir"检查的版本

如果需要先判断文件中是否包含ir再执行替换:

import re

target_word = "skaičius"

# 先检查文件内容
with open("tekstas.txt", "rt", encoding="utf-8") as f:
    file_content = f.read()
    if " ir " not in file_content:
        print("Nėra žodžio \"ir\".")
    else:
        # 重新打开文件执行替换
        with open("tekstas.txt", "rt", encoding="utf-8") as input_file, \
             open("naujasTekstas.txt", "wt", encoding="utf-8") as output_file:
            for line in input_file:
                processed_line = re.sub(r'\b\d+\b', target_word, line)
                output_file.write(processed_line)
        print("替换完成,结果已保存至naujasTekstas.txt")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:01:02