(练习)Python实例2:文件操作,字符串,替换敏感词

这篇博客介绍了一个Python实例,通过读取同目录下的`src.txt`文件,将其中包含的敏感词(参照`badwords.txt`)替换为星号(*),并将处理后的结果保存到新的`dst.txt`文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2-file-example.py
2-file-example-badwords.txt
2-file-example-src.txt
2-file-example-dst.txt

本文件同目录下两个文件
badwords.txt
src.txt
把src.txt中的敏感字替换为*并另存为dst.txt

import os

badwords_file = '2-file-example-badwords.txt'
src_file = '2-file-example-src.txt'
dst_file = '2-file-example-dst.txt'

# 执行当前文件时输入的路径
filepath = __file__
print(filepath)

# 替换为全路径
fullpath = os.path.realpath(__file__)
print(fullpath)

# 截取取全路径中的目录
curdir = os.path.dirname(os.path.realpath(__file__))
print(curdir)

# 敏感词
words = []
f = open(curdir+badwords_file, 'r') # mode='r' 只读就可以了
lines = f.readlines()
for line in lines:
	word = line.replace('\n', '') # 去'\n'
	words.append(word)
f.close()
print(words)

# 取源文件
f = open(curdir+src_file, 'r')
content = f.read()
f.close()

print(content)

# 遍历敏感词
for word in words:
	s = ''
	for i in range(0,len(word)):
		s += '*'
	content = content.replace(word, s)

print(content)

# 写目标文件
f = open(curdir+dst_file, 'w')
f.write(content)
f.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值