File1.txt :
File2.txt :
Expected output:
This is my code:
file1 = open ("file1.txt",'r')
file2 = open ("file2.txt",'r')
file1_lines=file1.readlines()
file2_lines=file2.readlines()
for j, line2 in enumerate (file2_lines):
for i in range (0,3):
if file1_lines[i] in line2:
print(line2)
Seems like i cannot make it iterate, im a beginner in coding, please point out why my code doesnt not working. Thank you :)
CodePudding user response:
Since it's file1 that determines the order, that has to be the outer loop.
file1 = open ("file1.txt",'r')
file2 = open ("file2.txt",'r')
file1_lines=file1.readlines()
file2_lines=file2.readlines()
for line1 in file1_lines:
for line2 in file2_lines:
if line2.startswith(line1):
print(line2)
CodePudding user response:
Solution 1
One way to solve this problem is to have an order table such as:
Make | Order |
---|---|
Honda | 00000000- |
Toyota | 00000001- |
BMW | 00000002- |
Ford | 00000003- |
Then, for each model, we replace "Honda" with "00000000-", "Toyota" with "00000001-", then sorting will be easy.
import itertools
# Create `order`: A dictionary to transform text in a format suitable
# for sorting
counter = itertools.count()
with open("file1.txt") as stream:
order = {key.strip(): f"{value:>08}-" for key, value in zip(stream, counter)}
# At this point, order looks something like:
# {'Honda': '00000000-',
# 'Toyota': '00000001-',
# 'BMW': '00000002-',
# 'Ford': '00000003-'}
def keyfunc(text):
"Translate Honda778 to 00000000-778, good for sorting."
for key, value in order.items():
text = text.replace(key, value)
return text
# Read a list of models and sort
with open("file2.txt") as stream:
models = stream.read().splitlines()
models.sort(key=keyfunc)
# Output
for model in models:
print(model)
The output:
Honda778
Toyota126
BMW99
Ford78x
Solution 2
In this solution, we will create a bucket
: A dictionary {make: list of models}
, that might look something like:
{'Honda': ['Honda778'],
'Toyota': ['Toyota126'],
'BMW': ['BMW99'],
'Ford': ['Ford78x']}
Then it is a matter of going through each list and print.
def get_make(model):
"""Given Toyota126, returns Toyota."""
for make in bucket:
if make in model:
return make
with open("file1.txt") as stream:
bucket = {key.strip(): [] for key in stream}
with open("file2.txt") as stream:
for model in stream:
model = model.strip()
bucket[get_make(model)].append(model)
# Output
for models in bucket.values():
print("\n".join(models))
While these solutions are somewhat long, I value long, but descriptive solutions over short, cryptic ones. Please comment.