[英]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.