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.

Community
  • 1
  • 1
Lucas
  • 93
  • 2
  • 12
  • How are the data arranged in the file? – Wiktor Stribiżew Dec 21 '16 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. – roganjosh Dec 21 '16 at 21:13

2 Answers2

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'}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
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
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48