繁体   English   中英

在文件中查找特定单词,获取行的内容,然后将其保存在数组中

[英]Find an specific word on a file, get the content of the row, and save it on a array

我有一个.xls文件,我将其转换为.csv,然后读取此.csv,直到包含单词clientegen特定行,获取该行并将其放在数组上。

到目前为止,这是我的代码:

import xlrd
import csv

def main():
    print "Converts xls to csv and reads csv"
    wb = xlrd.open_workbook('ejemplo.xls')
    sh = wb.sheet_by_name('Hoja1')
    archivo_csv = open('fichero_csv.csv', 'wb')
    wr = csv.writer(archivo_csv, quoting=csv.QUOTE_ALL)
    for rownum in xrange(sh.nrows):
        wr.writerow(sh.row_values(rownum))
    archivo_csv.close()

    f = open('fichero_csv.csv', 'r')
    for lines in f:
        print lines

if __name__ == '__main__':
    main()

这打印出我:

[... a lot of more stuff ...]

"marco 4","","","","","","","","","","","","","","",""

"","","","","","","","","","","","","","","",""

"","","","","","","","","","","","","","","",""

"clientegen","maier","embega","Jegan ","tapa pure","cil HUF","carcHUF","tecla NSS","M1 NSS","M2 nss","M3 nss","doble nss","tapon","sagola","clip volvo","pillar"

"pz/bast","33.0","40.0","34.0","26.0","80.0","88.0","18.0","16.0","8.0","6.0","34.0","252.0","6.0","28.0","20.0"

"bast/Barra","5.0","3.0","6.0","8.0","10.0","4.0","10.0","10.0","10.0","10.0","8.0","4.0","6.0","10.0","6.0"

[... a lot of more stuff ...]

我想做的是获取该clientegen行,并将该行的内容保存在一个名为finalarray的新字符串数组中。

finalarray = ["maier", "embega", "Jegan", "tapa pure", "cil HUF", "carcHUF", "tecla NSS", "M1 NSS", "M2 nss", "M3 nss", "doble nss", "tapon", "sagola", "clip volvo", "pillar"]

我对python文件的读/读不是很多,所以我想知道是否有人可以帮我找到那条线,获取那些值并将它们放在数组上。 提前致谢。

如果您只是在寻找包含clientegen的行,则可以尝试:

finalarray = list()
with open("fichero_csv.csv") as f:
  for line in f: #loop through all the lines
    words = line.split(" ") #get a list of all the words
    if "clientegen" in words: #check to see if your word is in the list
      finalarray = words #if so, put the word list in your finalarray
      break  #stop checking any further

如果您将此for循环交换为for循环,则应达到以下目的:

    for rownum in xrange(sh.nrows):
        row = sh.row_values(rownum)
        if row[0] == "clientegen":  # Check if "clientgen" is the first element of the row
            finalarray = list(row)  # If so, make a copy of it and name it `finalarray`
        wr.writerow(row)

如果将有多个“ clientegen”行,我们可以调整此代码以保存所有代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM