ValueError: apply_edit edit operations are invalid or inapplicable

本文介绍了如何在使用fuzzywuzzy和python-Levenshtein包时遇到的UTF-8编码问题,重点讲述了为何Levenshtein包处理非ASCII字符不兼容,并提供了相关解决方案和参考链接.

@创建于20220220
@修改于20220220

安装了fuzzywuzzy
且使用了 python-Levenshtein 包

from fuzzywuzzy import fuzz
s1 = ‘abc’
s2 = ‘🔪’
s3 = ‘马𨟠村民委员会’
print(fuzz.partial_ratio(s1, s2))
print(fuzz.partial_ratio(s1, s3))

不使用python-Levenshtein运行正确,使用则错误。

特别警示:

𨟠不能被python-Levenshtein包使用utf-8正确编译

原因:
python-Levenshtein package doesn’t handle UTF-8 input properly.

参考链接:FuzzyWuzzy throwing ValueError when reading string array

在使用 NumPy 的 `apply_along_axis` 函数时,遇到 **"Cannot apply_along_axis when any iteration dimensions are 0"** 错误,通常是因为输入的数组在指定的轴方向上维度为 0,导致无法进行函数应用。 ### 错误原因分析 NumPy 的 `apply_along_axis` 函数用于沿指定轴对数组的子数组应用某个函数。该函数的基本调用形式如下: ```python numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs) ``` 其中: - `func1d` 是一个接受 1-D 数组的函数。 - `axis` 指定沿哪个轴操作。 - `arr` 是输入的多维数组。 `apply_along_axis` 的工作机制是将数组在指定轴上切片,提取出多个一维数组,然后将 `func1d` 依次作用于这些切片上。如果数组在某个轴上的维度为 0(即该轴长度为 0),则无法进行切片,从而引发错误。 ### 示例说明 ```python import numpy as np # 合法案例 b = np.array([[1, 2, 3], [4, 5, 6]]) result = np.apply_along_axis(lambda x: x.sum(), 1, b) # 沿行方向求和 ``` ```python # 非法案例:维度为 0 的轴 c = np.array([], shape=(0, 3)) # 形状为 (0, 3) 的空数组 np.apply_along_axis(lambda x: x.sum(), 1, c) # 报错:Cannot apply_along_axis when any iteration dimensions are 0 ``` ### 解决方法 1. **检查输入数组是否为空或维度为 0** 在调用 `apply_along_axis` 前,确保数组在指定轴方向上长度大于 0: ```python if arr.shape[axis] > 0: result = np.apply_along_axis(func1d, axis, arr) else: result = np.array([]) # 或者根据需求处理空数组 ``` 2. **避免对空数组执行操作** 若数组可能为空,应在逻辑中提前处理空数组的情况,而不是直接调用 `apply_along_axis`。 3. **验证轴索引是否合法** 确保 `axis` 参数在数组维度范围内,例如对于二维数组,`axis` 只能是 `0` 或 `1`: ```python assert 0 <= axis < arr.ndim, "Axis out of bounds" ``` 4. **使用条件判断处理空数组** 对于可能为空的数组,可结合条件判断进行处理,例如: ```python if arr.size == 0: result = np.zeros_like(arr) else: result = np.apply_along_axis(func1d, axis, arr) ``` ### 优化建议 - **尽量使用 NumPy 的内置函数**:如 `np.sum()`、`np.mean()` 等,这些函数已经优化过,通常比 `apply_along_axis` 更高效。 - **函数应适配空数组输入**:自定义函数 `func1d` 应考虑输入为长度为 0 的数组时的行为,避免额外错误。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值