![](/img/trans.png)
[英]Python: “ImportError: no module named xlrd” after installing xlrd using pip
[英]How to remove strange characters while using regex and xlrd module Python
我正在尝试使用 xlrd 模块读取 Excel 文件的第二列。 但问题是第二列也有空白行。 我只需要选择值而不是行。 下面是我的代码:
import xlrd
import sys
import re
workbook_name = sys.argv[1]
if workbook_name:
book = xlrd.open_workbook(workbook_name)
for sheet in book.sheet_names():
if re.search(r'Munich',sheet):
sh = book.sheet_by_name(sheet)
#num_cols = sh.ncols
for row_ids in range(0,sh.nrows):
cell_obj = str(sh.cell(row_ids,1))
blank_regex = re.compile(r'u\'\'')
if not re.search(blank_regex,cell_obj):
#re.sub('^.+u'()',\1,cell_obj)
print(cell_obj)
else:
print ("Please supply workbook_name")
当我得到输出时,这就是我得到的:
text:u'Dom0'
text:u'muclgd0008.dedc2.cloud.com'
text:u'muclgd0007.dedc2.cloud.com'
text:u'muclgd0006.dedc2.cloud.com'
text:u'muclgd0005.dedc2.cloud.com'
text:u'muclgd0004.dedc2.cloud.com'
text:u'muclgd0003.dedc2.cloud.com'
text:u'Dom0'
text:u'muclmx0032.dedc2.cloud.com'
text:u'muclmx0031.dedc2.cloud.com'
text:u'muclmx0030.dedc2.cloud.com'
text:u'muclmx0029.dedc2.cloud.com'
text:u'muclmx0028.dedc2.cloud.com'
text:u'muclmx0027.dedc2.cloud.com'
text:u'muclmx0026.dedc2.cloud.com'
text:u'muclmx0025.dedc2.cloud.com'
text:u'muclgp0002.dedc2.cloud.com'
text:u'muclgp0001.dedc2.cloud.com'
text:u'Hardware Device'
text:u'Exadata X2-2 Quater Rack'
text:u'Exadata X2-2 Quater Rack'
text:u'ZFS Filer'
text:u'BDA'
我不知道为什么这个奇怪的文本:u'' 开始出现。这些字符不在 Excel 表中。
有人可以指导我如何删除它。
提前致谢。
你得到u
是因为你使用的是 Python 2,你得到引号是因为你打印出“单元格对象”(你隐式转换为它的“repr”),而不是它的值。 使用sh.cell_value()
而不是str(sh.cell())
。
一旦你这样做了,你就可以去掉空格并检查结果是否为非空:
if cell_text.strip():
print(cell_text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.