Python:在Excel文件中查找特定的单词或值

所以我给了两个excel文件,就像这个例子

movieId title genres 1 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy 2 Jumanji (1995) Adventure|Children|Fantasy 3 Grumpier Old Men (1995) Comedy|Romance 4 Waiting to Exhale (1995) Comedy|Drama|Romance 5 Father of the Bride Part II (1995) Comedy 

我试图做的事情是当某人键入标题代码将findmovieID和电影名称。 唯一的问题是我不知道从哪里开始我是一个noob编码器,我一直在尽我所能学习,但我不知道,如果你们可以帮助我,并指出我在正确的方向,这将是惊人的。

谢谢

好吧,既然你是一个noob编码器,我会以一种简单的方式向你解释,实际上并不需要任何库。 另外,我将假设您正在使用电影标题和名称互换。

首先,你可以把一个excel文件转换成一个.csv ,代表逗号分隔的文件(通过excel,只要另存为,selectcsv,你也可以通过谷歌表单来完成)。 什么是csv文件? 这就像excel文件,除了每一行都在一行上,不同的列由逗号分隔。 所以你的csv的前三行是:

 movieId,title,genres 1,Toy Story (1995),Adventure|Animation|Children|Comedy|Fantasy 2,Jumanji (1995),Adventure|Children|Fantasy 

现在,.csv可以作为常规文件读取。 你应该逐行阅读。 这是Python的文档。 这非常简单。

现在你已经将每一行都作为一个string了,我们可以通过string.split()命令来分割它们。 我们需要使用逗号作为分隔符,因为它是逗号分隔的文件。 到目前为止,我们的代码是这样的(我假设你阅读csv的不同行到lines数组中):

 lines = [...] # a list of strings which are the different lines of the csv name_im_looking_for = "move you like" # the movie you're looking for for(l in lines): columns = l.split(',') id = columns[0] name = columns[1] if(name.find(name_im_looking_for) != -1): # this means the name you're looking for is within the 'name' col print "id is", id, "and full name is", name 

这只是一个简单的方法,但是如果你真的是编程新手,应该可以帮助你顺利完成任务! 如果您有任何问题,请随时询问(如果您真的很好,而您只是想知道如何使用openpyxl,请在您的问题中指定)。

以下是你如何在openpyxl中做到这一点,因为你在你的问题中包含了openpyxl标签:

 import openpyxl as xl workbook = xl.load_workbook(filename="test.xlsx") title_column_name = "title" # Get the active worksheet ws = workbook.active # The String we'll search for. You could prompt the user to provide # this using python2's raw_input, oder python3's input function. searchstring = "Grumpier" # ws.rows[1:] means we'll skip the first row (the header row). for row in ws.rows[1:]: # row[1] is the title column. string.find(str) returns -1 # if the value was not found, or the index in the string if # the value was found. if row[1].value.find(searchstring) != -1: print("Found a matching row! MovieId={0}, Title={1}".format(row[0].value, row[1].value)) 

输出:

 Found a matching row! MovieId=3, Title=Grumpier Old Men (1995)