I have a word list contains in a text file; below I show an example:
place
lime
nest
land
I want to get an other file with the content below:
pl@ce
lim3
n3st
l@nd
This mean that:
- the letter
a
must be transform in in the char@
but in a word must be only 1 change soapart
becomesap@rt
and not@p@rt
. - the letter
e
must be transform in in the number3
This is first time that I use stackoverflow so sorry for my writing and for my English.
I'm also new to coding (python) so I might not understand all the code very well.
CodePudding user response:
Split input string into individual words, replace first instance of 'a' with '@' in each word. Append edited words to output string.
input = 'place lime nest land'
output = ''
input = input.split(' ')
for i in input:
i = i.replace('a', '@', 1)
i = i.replace('e', '3', 1)
output = i ' '
print(output)
Output:
@part pl@c3 lim3 n3st l@nd
CodePudding user response:
With regular expressions you can do
import re
s1 = re.sub(r'a(?=[^a]*?\b)', '@', 'apart place lime nest land')
s2 = re.sub(r'e(?=[^e]*?\b)', '3', s1)
print(s2)
Using the solution from this question. We can combine it into a single expression:
subs = {'a': '@', 'e': '3'}
pattern = re.compile(r'a(?=[^a]*?\b)|e(?=[^e]*?\b)')
s = pattern.sub(lambda x: subs[x.group()], 'apart place lime nest land')
print(s)
Output:
ap@rt pl@c3 lim3 n3st l@nd
This replaces the last letter a
and last letter e
within a word.
CodePudding user response:
Input from file, output to file
This code read words from the file file1.txt
and write the changed word on file2.txt
:
with open('file1.txt') as f:
with open('file2.txt', 'w') as f2:
for word in f:
word = word.replace("a", "@", 1)
word = word.replace("e", "3", 1)
f2.write(word)
This change only the first occurrance of a letter, so apart
becomes @part
.
CodePudding user response:
Reverse the string, replace first occurence, then reverse the string back. (Hardcoded)
print('apart place lime nest land'[::-1].replace('a', '@', 3).replace('e', '3',2)[::-1])
# ap@rt pl@ce lim3 n3st l@nd
CodePudding user response:
this may be a rough first draft and some assumptions were made but here is a shot at a function. Could be cleaned up alot. Good luck
def updt_text(s):
# assumptions, string of text is seperated by spaces and there are no odd characters
words = s.split()
newwords = []
dictChanges = {
'a': '@',
'e': '3',
}
for word in words:
for k, v in dictChanges.items():
if k in word:
word = word.replace(k, v)
break
newwords.append(word)
return newwords