Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
laurensvanhaecke
Courses Plus Student 899 PointsFunction censor()
The function censor() takes the name of a file (a string) as input. The function should open the file, read it, and then write it into file censored.txt with this modifi- cation: Every occurrence of a four-letter word in the file should be replaced with string 'xxxx'.
I'm working on some problems for my own benefit. However, I'm not sure what to do here. I believe the function has to go something like this but I get lost... anyone have any clue what to do next here?
def censor(filename):
infile = open(filename)
content = infile.read()
infile.close()
censor("censored.txt")
Am I supposed to enter a string in somewhere? I don't have the actual file..like I said I'm just doing extra problems. Or an if statement selecting the first four characters?
Thanks.
1 Answer
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi Laurens
This is how i attempted it.
def censor(readfile,writefile,mode='r+'):
infile = open(readfile,mode)
outfile = open(writefile,mode)
new_list=[]
for line in infile:
mylist = line.split()
for word in mylist:
if string_count(word):
word ="XXXX "
else:
pass
new_list.append(word)
for word in new_list:
outfile.write("{} \n".format(word))
infile.close()
outfile.close()
def string_count(mystring):
if len(mystring)==4:
return True
else:
return False
censor("filetoreadfrom.txt","censored.txt")
this assumes both files are in the same directory
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsAndreas cormack
Python Web Development Techdegree Graduate 33,011 PointsI have edited your code for more readability. Refer to the markdown cheatsheet below to know how to format your posts.