1

Ive got this code from replacing text in a file with Python

import re
repldict = {'zero':'0', 'one':'1' ,'temp':'bob','garage':'nothing'}
def replfunc(match):
    return repldict[match.group(0)]

regex = re.compile('|'.join(re.escape(x) for x in repldict))
with open('file.txt') as fin, open('fout.txt','w') as fout:
    for line in fin:
        fout.write(regex.sub(replfunc,line))

but i cant load the repldict from other txt file. i've tried with

repldict={line.strip() for line in open(syspath+'/rules.txt', 'r')}

But it doesn't work.

2
  • How are the data arranged in the file? Commented Dec 21, 2016 at 21:12
  • 1
    It looks like you're trying to create a dictionary via dictionary comprehension? repldict={line.strip() for line in open(syspath+'/rules.txt', 'r')}. This doesn't have key, value pairs that I can see. A guess: You need to load the file, split each line by its delimiter (e.g. a comma, space) and then use indexing to decide which word is the key, and which word is the value that should be used as a substitute for the word you've defined as the key. Commented Dec 21, 2016 at 21:13

2 Answers 2

3

If the dictionary file has the following simple format:

zero 0
one 1
temp bob
garage nothing

You can create your dictionary using split (not strip, split without parameters has an integrated strip feature somehow) in a generator comprehension which yields tuples (key,value), passed to dict:

repldict=dict(line.split() for line in open(os.path.join(syspath,"rules.txt"), 'r'))

result:

{'temp': 'bob', 'one': '1', 'garage': 'nothing', 'zero': '0'}
Sign up to request clarification or add additional context in comments.

Comments

1

Considering that your 'rules.txt' file looks like:

zero:0
one:1
temp:bob
garage:nothing

then:

with open(syspath+'/rules.txt', 'r') as rules:
    repldict={}
    for line in rules:
        key, value = line.strip().split(':')
        repldict[key] = value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.