簡體   English   中英

Python:在Excel文件中查找特定的單詞或值

[英]Python: Looking for specific word or values in an excel file

所以我得到了兩個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

我要嘗試做的是,當有人鍵入標題時,代碼將找到movieID和電影名稱。 唯一的問題是我不知道從哪里開始我是一個菜鳥編碼者,我一直在努力學習,但是我不知道,如果你們可以幫助我並指出正確的方向,那將是驚人的。

謝謝

好的,因為您是菜鳥編碼者,所以我將以一種實際上不需要任何庫的簡單方式向您解釋。 我還要假設您正在交替使用電影標題和名稱。

首先,您可以將excel文件轉換為.csv ,代表用逗號分隔的文件(通過excel,只需另存為,然后選擇csv即可。您也可以通過Google表格來完成此操作)。 什么是csv文件? 就像excel文件一樣,不同之處在於每一行本身都是一行,並且不同的列之間用逗號隔開。 因此,csv中的前三行將是:

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

現在,.csv可以作為常規文件讀取。 您應該逐行閱讀它們。 是用於的python文檔。 非常簡單。

現在您已經將每一行都作為字符串,我們可以通過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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM