Hi,
I have a list of keywords, for example: cat, dog, turtle, etc x2000.
I have a chunk of code saved to a txt file:
Which happens to be JS with MongoDB syntax, but input data shouldn't matter.
'submit #dnMARKERSubmitter':function(e){
e.preventDefault();
var MARKER = $('#dnMARKER').val();
MyDatabase.insert({
MARKER: MARKER,
createdAt: new Date()
});
},
Actually I have several chucks of code on 4 different files that make the CRUD system work as I need it, but for simplicity sake let's just say i have this one chunk.
In sublime 3 text editor, I can manually Find All "MARKER" & Replace with "Cat"... copy chunk and paste into My.js file. Rinse Repeat "Dog", "Turtle", x2000.
That will be too tedious. So I've discovered Python, and this .py code works beautifully as a "find & replace" substitute process:
word_list = {'MARKER' : 'Cat'}
with open("/Users/me/Desktop/findreplaceprocess/ChunkofCode.txt") as main:
with open('/Users/me/Desktop/findreplaceprocess/NewChunk.txt', 'w') as new_main:
input_data = main.read()
for key, value in word_list.iteritems():
input_data = input_data.replace(key, value)
new_main.write(input_data)
I'm struggling to modify the "for x in y" so that I can have it loop through keywords "Cat, Dog, Turtle, etc." to output:
'submit #dnCatSubmitter':function(e){
e.preventDefault();
var Cat = $('#dnCat').val();
MyDatabase.insert({
Cat: Cat,
createdAt: new Date()
});
},
'submit #dnDogSubmitter':function(e){
e.preventDefault();
var Dog = $('#dnDog').val();
MyDatabase.insert({
Dog: Dog,
createdAt: new Date()
});
},
'submit #dnTurleSubmitter':function(e){
e.preventDefault();
var Turle = $('#dnTurle').val();
MyDatabase.insert({
Turle: Turle,
createdAt: new Date()
});
},
etc x2000.
I fear it will take me nearly as long to learn by "research --> tutorial --> trial & error" as it would for me to manually find & replace the words. That's why I'm hoping by reaching out to you, some kind soul will help solve my immediate problem. I know I should learn Python through and through.... And will, once I get to my arduino/Raspberry Pi project.
Thank you in advance.
E1 Perhaps I should mention that I'm on py --version 2.7.10 ATM.
E2 Found another py code that seams more eloquent, but fails to loop through the list of words.
words = open("/Users/me/Desktop/findreplaceprocess/doc1.txt", "r").readlines()
code = open("/Users/me/Desktop/findreplaceprocess/doc2.txt", "r").read()
output = open("/Users/me/Desktop/findreplaceprocess/doc3.txt", "w")
for word in words: code = code.replace("MARKER", word)
output.write(code)
Subreddit
Post Details
- Posted
- 8 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnprogra...