我需要驗證在相應的 .txt 中是否存在滿足這兩個匹配項的行:
file1.txt與輸入 string1 相同的檔案名的行"old apple"。file2.txt與輸入 string2 相同的檔案的行"on the floor"。
例如,file1.txt有這些行:
juicy orange
old apple
rusty key
old apple
modern table
old apple
例如,file2.txt有這些其他行:
in a box
on the chair
on the bed
on the floor
on the floor
under the desktop
在這種情況下,正確的行是第 4 行,即索引為 3 的行
這是我的代碼,但我遇到了相互匹配要求的問題
string1 = "old apple"
string2 = "on the floor"
num_linea_data_field_1 = None
num_linea_data_field_2 = None
validation_data_field_1 = False
validation_data_field_2 = False
with open("file1.txt","r ") as f:
lineas = [linea.strip() for linea in f.readlines()]
if (string1 not in lineas):
pass
else:
num_linea_data_field_1 = lineas.index(string1)
validation_data_field_1 = True
with open("file2.txt","r ") as f:
lineas = [linea.strip() for linea in f.readlines()]
if (string1 not in lineas):
pass
else:
num_linea_data_field_2 = lineas.index(string2)
validation_data_field_2 = True
if(validation_data_field_1 == True and validation_data_field_2 = True):
print("Mutual coincidence condition is satisfied with these inputs!")
else:
print("Mutual coincidence condition is not satisfied with these inputs!")
如果輸入之一匹配但在檔案的不同行上,則此代碼將失敗。
我該如何處理這種雙重匹配演算法?
uj5u.com熱心網友回復:
在您的代碼中,您只檢查字串是否存在于相應的串列中,您不檢查相應的行號是否匹配。但即使你檢查一下,你的代碼也可能會因為.index作業原理而產生錯誤的輸出。從這里參考:
list.index(x[, start[, end]])回傳值等于的第一項的串列中從零開始的索引
x。ValueError如果沒有這樣的專案,則引發 a 。...
你只會得到第一個索引。所以,如果沒有與相應的第一個發現匹配的行號,你就會被卡住。
如果您只對是否有匹配感興趣,那么您可以執行以下操作:
with open("file1.txt", "r") as file1,\
open("file2.txt", "r") as file2:
matches = any(
row1.strip() == string1 and row2.strip() == string2
for row1, row2 in zip(file1, file2)
)
if matches:
print("Mutual coincidence condition is satisfied with these inputs!")
else:
print("Mutual coincidence condition is not satisfied with these inputs!")
如果您還對提供匹配項的行號感興趣:
with open("file1.txt", "r") as file1,\
open("file2.txt", "r") as file2:
matches = [
i for i, (row1, row2) in enumerate(zip(file1, file2), start=1)
if row1.strip() == string1 and row2.strip() == string2
]
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433681.html
標籤:Python python-3.x 细绳 验证 读取文件
