如何在使用正则表达式和 xlrd 模块时删除奇怪的字符 Python

How to remove strange characters while using regex and xlrd module Python

我正在尝试使用 xlrd 模块读取 excel 文件的第二列。但问题是第二列也有空行。我只需要 select 值而不是行。下面是我的代码:

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'()',,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'

我不确定为什么这个奇怪的 text:u'' 出现在 beginning.These 字符中,而 excel sheet.

中没有

谁能指导我如何删除它。

提前致谢。

你得到 u 是因为你使用的是 Python 2,你得到引号是因为你打印出 "cell object"(你隐式转换到它的 "repr"),而不是它的值。使用 sh.cell_value() 而不是 str(sh.cell()).

完成后,您可以去掉空格并检查结果是否为非空:

if cell_text.strip():
    print(cell_text)