【问题标题】:Handling special characters from Excel to CSV using Python使用 Python 处理从 Excel 到 CSV 的特殊字符
【发布时间】:2019-11-14 12:31:41
【问题描述】:

您好,我在使用 python 处理从 Excel 工作表到 CSV 的特殊字符时遇到问题 当我使用

else:
                    # Encode strings into format to preserve content of cell
                    row_values.append(cell.value.encode("UTF-8").strip())

我得到了特殊字符'Â'

当我使用

  else:
                    # Encode strings into ISO-8859-1 format to preserve content of cell
                    row_values.append(cell.value.encode("iso-8859-1").strip())

'�' 的特殊字符好说吗?钻石

我相信这与编码有关,但不确定使用哪一个。这些字符来自转换为 CSV 的 Excel 工作表。

这是我使用的代码

def convert_to_csv(excel_file, input_dir, output_dir):
    """Convert an excel file to a CSV file by removing irrelevant data"""
    try:
        sheet = read_excel(excel_file)
    except UnicodeDecodeError:
        print 'File %s is possibly corrupt. Please check again.' % (excel_file)
        sys.exit(1)
    row_num = sheet.get_highest_row()  # Number of rows
    col_num = sheet.get_highest_column()  # Number of columns
    all_rows = []
    # Loop through rows and columns
    for row in range(row_num):
        row_values = []
        for column in range(col_num):
            # Get cell element
            cell = sheet.cell(row=row, column=column)
            # Ignore empty cells
            if cell.value is not None:
                if type(cell.value) == int or type(cell.value) == float:
                    # String encoding not applicable for integers and floating point numbers
                    row_values.append(cell.value)
                else:
                    # Encode strings into ISO-8859-1 format to preserve content of cell
                    row_values.append(cell.value.encode("iso-8859-1").strip())
            else:
                row_values.append('')
        # Append rows only having more than three values each
        if len(set(row_values)-{''}) > 3:
            # print row_values
            all_rows.append(row_values)
    # Saving the data to a csv extension with the same name as the given excel file
    output_path = os.path.join(output_dir, excel_file.split('.')[0] + '.csv')
    with open(output_path, 'wb') as f:
        writer = csv.writer(f, delimiter=";", quoting=csv.QUOTE_ALL)

        writer.writerows(all_rows[1:])

使用 Python 2.6.9 想知道我们是否可以在写入 CSV 之前使用正则表达式 无论如何我们可以处理这个吗?

提前致谢。

【问题讨论】:

    标签: python regex export-to-csv


    【解决方案1】:

    搞定了

               ` else:
                    # Encode strings into ISO-8859-1 format to preserve content of cell
                    row_values.append(
                        re.sub(r'[^\x00-\x7f]', r'', cell.value).strip())`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-22
      相关资源
      最近更新 更多