在python中替换四个字母的单词 [英] Replace four letter word in python
问题描述
我正在尝试编写一个程序来打开一个文本文档并用 ** 替换所有四个字母的单词.我已经折腾了这个程序好几个小时了.我似乎无处可去.我希望有人能够帮助我解决这个问题.这是我到目前为止所拥有的.非常感谢帮助!
I am trying to write a program that opens a text document and replaces all four letter words with **. I have been messing around with this program for multiple hours now. I can not seem to get anywhere. I was hoping someone would be able to help me out with this one. Here is what I have so far. Help is greatly appreciated!
def censor():
filename = input("Enter name of file: ")
file = open(filename, 'r')
file1 = open(filename, 'w')
for element in file:
words = element.split()
if len(words) == 4:
file1 = element.replace(words, "xxxx")
alist.append(bob)
print (file)
file.close()
这里是改版的,不知道会不会好很多
here is revised verison, i don't know if this is much better
def censor():
filename = input("Enter name of file: ")
file = open(filename, 'r')
file1 = open(filename, 'w')
i = 0
for element in file:
words = element.split()
for i in range(len(words)):
if len(words[i]) == 4:
file1 = element.replace(i, "xxxx")
i = i+1
file.close()
推荐答案
for element in file:
words = element.split()
for word in words:
if len(word) == 4:
etc etc
原因如下:
说你文件的第一行是你好,我的名字是约翰"然后对于循环的第一次迭代:element = 'hello, my name is john'
和 words = ['hello,','my','name','is','john']
say the first line in your file is 'hello, my name is john'
then for the first iteration of the loop: element = 'hello, my name is john'
and words = ['hello,','my','name','is','john']
你需要检查每个单词里面的内容,因此for word in words
You need to check what is inside each word thus for word in words
另外值得注意的是,在您当前的方法中,您不注意标点符号.注意上面words
中的第一个词...
Also it might be worth noting that in your current method you do not pay any attention to punctuation. Note the first word in words
above...
要去掉标点符号,而是说:
To get rid of punctuation rather say:
import string
blah blah blah ...
for word in words:
cleaned_word = word.strip(string.punctuation)
if len(cleaned_word) == 4:
etc etc
这篇关于在python中替换四个字母的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!