Reputation: 91
if I have a text file contains all english alphabets with some corresponding value like the following:
A 0.00733659550399
B 0.00454138879023
C 0.00279849519224
D 0.00312734304092
.
.
.
I want to assign these numeric values to each line I'm reading from another txt file.
L = open(os.path.join(dir, file), "r").read()
line = L.rstrip()
tokens = line.split()
for word in tokens:
for char in word:
find
Upvotes: 0
Views: 664
Reputation: 87124
Create a dictionary from the first file like this:
with open('values.txt') as f:
values = {k:v for k,v in (line.split() for line in f)}
Then iterate over each character of the data file and replace it with the corresponding value:
with open('A.txt') as infile, open('output.txt', 'w') as outfile:
for line in infile:
for c in line.rstrip():
print(values.get(c.upper(), '0'), file=outfile)
This code (assumes Python 3 or import of print function in Python 2) will write to output.txt
the numeric values corresponding to the input characters, one per line. If there is no value for a character, 0
is output (that can be changed to whatever you want). Note that the incoming characters are converted to upper case because your sample looks like it might comprise upper case letters only. If there are separate values for lower case letters, then you can remove the call to upper()
.
If you would prefer the values to remain on the same line then you can alter the print()
function call:
with open('A.txt') as infile, open('output.txt', 'w') as outfile:
for line in infile:
print(*(values.get(c.upper(), '0') for c in line.rstrip()), file=outfile)
Now the values will be space separated.
Upvotes: 2
Reputation: 2891
Is this what you're looking for ?
input.txt
AAB BBC ABC
keyvalue.txt
A 123
B 456
C 789
script.py
def your_func(input_file):
char_value = {}
with open('keyvalue.txt', 'r') as f:
for row in f:
char_value[row.split()[0]] = row.split()[1]
res = []
with open(input_file) as f:
for row in f:
for word in row.split():
for c in word:
# Little trick to append only if key exists
c in char_value and res.append(char_value[c])
return '*'.join(res)
print(your_func("input.txt"))
# >>> 123*123*456*456*456*789*123*456*789
Upvotes: 1