如何在Python中执行以下操作:让我比较文本文件和excel文件,看看它们是否包含相同的数据?我有下面的代码(底部)设置,它只查找模型,如果它在文本文件中,它会打印出模型,品牌和类型在那里,但有时有多个相同的模型(不要问为什么),所以我如何输出
我宁愿让它从excel表格中取出一行/单元格,并将其与文本文件的每一行进行比较,如果其中包含相同的数据,则打印出这两行,但我不确定如何执行该操作。另外,如果excel中有一个空行,我怎么跳过它呢
我有一个包含以下内容的文本文件
Toyota sedan Corrola
Honda sedan Accord
Honda SUV CR-V
Toyota sedan Camry
Toyota sedan Avalon
Honda SUV Camry
以及包含以下内容的excel文件:
代码:
import pandas as pd
file1 = 'cars.xls'
file2 = open("cars.txt", "r")
df = pd.read_excel(file1, header=0)
readfile = file2.read()
for count in range(len(df['Brand'])):
if not str(df['Brand'][count]):
print("Blank line" + str(count))
print()
continue
model = str(df['model'][count])
model2 = model.replace(' ', '') # get rid of spaces in case there are any
if model2 in readfile:
print(str(df['Brand'][count]) + str(df['type'][count]) + str(df['model'][count]) + " is in both Excel sheet and text file")
期望输出:(无特定订单) 丰田轿车Corrola位于Excel表格和文本文件中 本田SUV CR-V位于Excel表格和文本文件中 丰田轿车凯美瑞位于Excel表格和文本文件中 本田SUV凯美瑞位于Excel表格和文本文件中 日产轿车Altima不在Excel表格和文本文件中
等 等
将文本文件的内容转换为数据框,然后检查它们是否相等。您可以调整如下内容:
相关问题 更多 >
编程相关推荐