![](/img/trans.png)
[英]Get relative path of file1 (relative to path of file2, file1 is in subfolder of file2)
[英]I have 2 files. File1 consist of car name and file2 consist of the car model. How do i get file2 to have the same arrangement as file1?
文件1.txt:
文件2.txt:
预计 output:
这是我的代码:
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)
好像我不能让它迭代,我是编码的初学者,请指出为什么我的代码不起作用。 谢谢:)
由于决定顺序的是 file1,因此它必须是外循环。
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)
解决这个问题的一种方法是有一个订单表,例如:
制作 | 命令 |
---|---|
本田 | 00000000- |
丰田 | 00000001- |
宝马 | 00000002- |
福特 | 00000003- |
然后,对于每个 model,我们将“Honda”替换为“00000000-”,将“Toyota”替换为“00000001-”,这样排序就很容易了。
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)
output:
Honda778
Toyota126
BMW99
Ford78x
在这个解决方案中,我们将创建一个bucket
:一个字典{make: list of models}
,它可能看起来像:
{'Honda': ['Honda778'],
'Toyota': ['Toyota126'],
'BMW': ['BMW99'],
'Ford': ['Ford78x']}
然后是遍历每个列表并打印的问题。
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))
虽然这些解决方案有些长,但我更看重冗长但具有描述性的解决方案,而不是简短、晦涩的解决方案。 请给出意见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.