Reputation: 63
I know I'm a newbie in programming but I'd like to write a Python script to censor some data.
My inputfile in structured like this:
username:password
username:p4ssw0rd
mail:pa3386
I need to censor all characters after the first 2-3 character right after the colon ":"
The results should be something like this:
username:pass****
username:p4ss**
mail:pa88***
Is there a way to do this?
I've been struggling a lot and tried with strip or split but i'm not able to get this to work...
f = open("myfile.txt",'r')
#result = [x.strip() for x in my_string.split(',')]
strings = f.read().strip()
print(strings)
targets = strings.split(':')
print(targets)
for x in range(len(strings)):
strings[x].strip()
print(strings)
lines = f.read().split('\n')
length = len(lines)
print(length)
for x in range(length):
print(strings[x])
Upvotes: 1
Views: 417
Reputation: 1012
Hope this will work:
f = open("myfile.txt", 'r')
lines = f.read().split('\n') # Get all lines of files (pairs of `key: value`)
result = [] # Result of "censoring", will be same format as input
for i in lines: # Loop each line
data = i.split(':') # Split, data[0] is a key and data[1] is a value (what we need to censor)
result.append(data[0] + ':' + data[1][0:3] + '***') # Censor, leaving only three first characters
# TODO: Handle situations when value is less when 3 symbols
final = '\n'.join(result); # Join lines together
# TODO: Write `final` to file or do something with it
f = open("myfile.txt",'r')
strings = f.read().strip() # All contents of file, removed extra spaces at end and at start
targets = strings.split(':') # From file:
# a:b
# c:d
# Will get ['a', 'b\nc', 'd']
for x in range(len(strings)): # Loop each character in input file (remember `strings` is .read().split())
strings[x].strip() # Nothing is did at this cycle, .strip() just returns copy
# For what was `strings` and `targets` defined?
lines = f.read().split('\n') # Get all lines in the file
# Print file line-by-line
lenght = len(lines)
print(lenght)
for x in range(lenght):
print(strings[x])
So, in original code, all the algorithm was missing. I could not explain anything instead of "Algorithm was missing". Sorry.
Upvotes: 2