无法从Python中的字符串中替换/删除\xa0(从Excel解析)

2024-09-27 21:23:32 发布

您现在位置:Python中文网/ 问答频道 /正文

    from collections import Counter
    from openpyxl import load_workbook

    nomefile = 'SerieA18_19.xlsx'

    wb = load_workbook(nomefile)
    ws = wb.worksheets
    sheet = wb.active
    max_row = sheet.max_row

    results = []
    for i in range(1, max_row + 1):
      cell_obj = sheet.cell(i, 1).value
      cell_obj.strip()
      cell_obj.replace('\\xa0', ' ')
      if cell_obj[2:3] == '-':
         results.append(cell_obj)
      if cell_obj[3:4] == '-' and cell_obj[:1] != '(':
         results.append(cell_obj)


    results_counter = Counter()
    for response in results:
       results_counter.update(response.split(','))

    print(results_counter)

结果如下: 计数器({'1\xa0-\xa01':44,'2\xa0-\xa01':39,'1\xa0-\xa00':35,'0\xa0-\xa00':34,'2\xa0-\xa00':28,'0\xa0-\xa01':

我无法删除/替换这些可能来自Excel文件的“\xa0”


Tags: fromimportobjcounterloadcellresultsmax
1条回答
网友
1楼 · 发布于 2024-09-27 21:23:32

python中的字符串是不可变的。您需要将该值分配给变量。 替换

cell_obj.strip()
cell_obj.replace('\\xa0', ' ')

  cell_obj = cell_obj.strip().replace(u'\xa0', u' ')

\xa0实际上是拉丁文1(ISO 8859-1)中的不间断空格,也是chr(160)。 当.encode('utf-8')时,它会将unicode编码为utf-8,这意味着每个unicode可以由1到4个字节表示。在这种情况下,\xa0由2个字节\xc2\xa0表示

仔细阅读http://docs.python.org/howto/unicode.html

相关问题 更多 >

    热门问题