简体   繁体   English

在python中使用xlrd从xls提取数据

[英]data extraction from xls using xlrd in python

I am trying to extract the data from an .xls file and making a list but i am getting the list as [u'elem1', u'elem2', u'elem3'] , but if i print separately i get as: 我正在尝试从.xls文件中提取数据并制作一个列表,但是我将列表获取为[u'elem1', u'elem2', u'elem3'] ,但是如果我单独打印,则会得到:

elem1
elem2
elem3

what is that u thing and how to remove it? 你的东西是什么以及如何将其删除?

Here is my code... 这是我的代码...

from xlrd import open_workbook
xls=open_workbook('name.xls')
for sheets in xls.sheets():
    list1=[]
    for col in range(sheets.ncols):
        for rows in range(sheets.nrows):
            list1.append(sheets.cell(rows, col).value)
print(list1)
for i in list1:
    print(i)

You can define the text as string,while appending data to the list in list1.append(str(sheets.cell(rows, col).value)) to remove [u' .The code will be: 您可以将文本定义为字符串,同时将数据追加到list1.append(str(sheets.cell(rows,col).value))中的列表中以删除[u' 。代码将为:

   from xlrd import open_workbook
   xls=open_workbook('name.xls')
   for sheets in xls.sheets():
   list1=[]
   for col in range(sheets.ncols):
      for rows in range(sheets.nrows):
         list1.append(str(sheets.cell(rows, col).value))
   print(list1)
   for i in list1:
      print i

Assuming you are using Python 2.x, the u thing says that xlrd gives you unicode strings (what Excel strings really are). 假设你正在使用Python 2.x中,在u的事情说xlrd让你Unicode字符串(什么Excel中的字符串真的是)。 If you want to convert them in Python 2.7 strings, you have to encode them with the charset you use 如果要将它们转换为Python 2.7字符串,则必须使用您使用的字符集对其进行编码

Assuming you use latin1 (also knows as iso-8859-1 or (with minimal differences) windows-1252, you can transform your list of unicode strings in a list of latin1 strings that way : 假设您使用latin1(也称为iso-8859-1或(具有最小差异)windows-1252),则可以通过以下方式在latin1字符串列表中转换unicode字符串列表:

strlist = [ elt.encode('latin1') for elt in list1 ]

or if you have only ASCII characters 或者如果您只有ASCII字符

strlist = [ str(elt) for elt in list1 ]

我通过做解决了

str(variable_name)

For practical matters, the u in the beginning won't affect u. 对于实际问题,开头的u不会影响u。 U can work with them as well unless you have some issues related to encoding it in different formats. 除非您在使用不同格式编码时遇到一些问题,否则U也可以与他们合作。

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

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