基本上,我想要一个打开文件的脚本,然后浏览该文件并查看该文件是否包含任何诅咒词.如果文件中的一行包含诅咒词,那么我想用"CENSORED"替换该行.到目前为止,我认为我只是搞砸了代码,因为我是Python的新手:
filename = input("Enter a file name: ")
censor = input("Enter the curse word that you want censored: ")
with open(filename)as fi:
for line in fi:
if censor in line:
fi.write(fi.replace(line, "CENSORED"))
print(fi)
Run Code Online (Sandbox Code Playgroud)
我是新手,所以我可能只是搞砸了......
行,如在此代码中(如果"Hat"是一个诅咒词):
There Is
A
Hat
Run Code Online (Sandbox Code Playgroud)
将会:
There Is
A
CENSORED
Run Code Online (Sandbox Code Playgroud)
您无法写入您正在阅读的同一文件,原因有两个:
您以只读模式打开文件,无法写入此类文件.您必须以读写模式(使用open(filename, mode='r+'))打开文件才能执行您想要的操作.
您正在阅读时替换数据,其中的行最有可能更短或更长.你不能在文件中这样做.例如,替换词cute具有censored将创建一个更长的线,这将覆盖不只是旧线,但开始下一行也是如此.
您需要将更改的行写出到新文件,并在该过程结束时将旧文件替换为新文件.
请注意,您的replace()通话也不正确; 你在线上叫它:
line = line.replace(censor, 'CENSORED')
Run Code Online (Sandbox Code Playgroud)
实现目标的最简单方法是使用fileinput模块 ; 它会允许你就地替换文件,因为它将处理写入另一个文件和文件交换:
import fileinput
filename = input("Enter a file name: ")
censor = input("Enter the curse word that you want censored: ")
for line in fileinput.input(filename, inplace=True):
line = line.replace(censor, 'CENSORED')
print(line, end='')
Run Code Online (Sandbox Code Playgroud)
这个print()电话有点神奇; 该fileinput模块暂时替换将写入替换文件而不是您的控制台的sys.stdout含义print().该end=''通知print()不包括换行; 该换行符已经line是输入文件原始读取的一部分.
| 归档时间: |
|
| 查看次数: |
989 次 |
| 最近记录: |