根据两个相似性矩阵的行标和列标,筛选两个相似性txt方矩阵共同存在的数据 并输出txt矩阵 python
时间: 2023-08-18 19:06:09 浏览: 73
以下是一个简单的实现:
```python
def load_similarity_matrix(file_path):
"""从txt文件中加载相似性矩阵"""
with open(file_path, "r") as f:
lines = f.readlines()
matrix = []
for line in lines:
row = [float(x) for x in line.strip().split()]
matrix.append(row)
return matrix
def filter_similarity_matrices(matrix1, matrix2):
"""根据两个相似性矩阵的行标和列标,筛选共同存在的数据"""
filtered_matrix1 = []
filtered_matrix2 = []
for i in range(len(matrix1)):
row1 = matrix1[i]
row2 = matrix2[i]
filtered_row1 = []
filtered_row2 = []
for j in range(len(row1)):
if row1[j] != 0 and row2[j] != 0:
filtered_row1.append(row1[j])
filtered_row2.append(row2[j])
filtered_matrix1.append(filtered_row1)
filtered_matrix2.append(filtered_row2)
return filtered_matrix1, filtered_matrix2
def save_similarity_matrix(matrix, file_path):
"""保存相似性矩阵到txt文件"""
with open(file_path, "w") as f:
for row in matrix:
line = " ".join(str(x) for x in row)
f.write(line + "\n")
# 加载相似性矩阵1
matrix1 = load_similarity_matrix("matrix1.txt")
# 加载相似性矩阵2
matrix2 = load_similarity_matrix("matrix2.txt")
# 筛选共同存在的数据
filtered_matrix1, filtered_matrix2 = filter_similarity_matrices(matrix1, matrix2)
# 保存筛选后的相似性矩阵1
save_similarity_matrix(filtered_matrix1, "filtered_matrix1.txt")
# 保存筛选后的相似性矩阵2
save_similarity_matrix(filtered_matrix2, "filtered_matrix2.txt")
```
这个实现假设两个相似性矩阵的行数和列数都相同。如果行数和列数不同,需要对实现进行修改。
阅读全文