python - 由于德语变音,Python 中的字符串不相等

标签 python string unicode-normalization

我尝试与字符串进行比较,两者都包含德语元音变音“ü”。两者看起来完全一样,也没有尾随 \n 或类似的内容。

enter image description here

其中一个位是从 xml 文件读取的,另一个位是从文件系统读取的。逐个字母地比较它们,显示出与元音变音的区别。

enter image description here

扭曲的元音变音(由两个字母、一个正常的 u 和两个上面的点组成)来自文件系统。我正在使用 macOS High Sierra 并运行 Python 3.7。使用 os.listdir() 读取文件名。

我很感激处理这种奇怪行为的建议(摆脱“ü”不是一个选择)。

最佳答案

不要直接比较字符串,而是在给定相同的 form 参数的情况下比较它们的 unicodedata.normalize 结果

来自文档:Comparing strings

A second tool is the unicodedata module’s normalize() function that converts strings to one of several normal forms, where letters followed by a combining character are replaced with single characters. normalize() can be used to perform string comparisons that won’t falsely report inequality if two strings use combining characters differently

import unicodedata

def compare_strs(s1, s2):
    def NFD(s):
        return unicodedata.normalize('NFD', s)

    return NFD(s1) == NFD(s2)

关于python - 由于德语变音,Python 中的字符串不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59892754/

相关文章:

python - Seaborn/Matplotlib - 仅在 FacetGrid 中显示某些 X 值

python - 将 PCL 链接到 Cython C++ 模块

python - 从列表中创建 pyspark 数据框列,其中列表的长度与数据框的行数相同

c - 中止陷阱 : 6 in C when using strcpy on MacOS

java - 如何删除单词周围的字符?

python - 在 PySpark 中使用 Apache Spark 数据帧删除重音的最佳方法是什么?

python - uWSGI项目未启动--/tmp/logs/uwsgi.log权限被拒绝[core/logging.c第28行]

javascript - 将字符串拆分为单词数组以查找最长的

java - 如何规范化 Java 中的 Unicode 数字