比较单词与特殊字符(é、è、...)时忽略变音符号

发布于 2024-09-08 15:26:17 字数 350 浏览 6 评论 0原文

我有一个包含一些带有变音符号的比利时城市的列表:(列日、Quiévrain、Franière 等),我想转换这些特殊字符以与包含大写相同名称但没有变音符号的列表进行比较( LIEGE、QUIEVRAIN、FRANIERE)

我首先尝试做的是使用大写:

LIEGE.contentEqual(Liège.toUpperCase()) 但这不适合,因为 的大写列日LIÈGE而不是LIEGE

我有一些复杂的想法,比如替换每个角色,但这听起来很愚蠢而且是一个漫长的过程。

关于如何以聪明的方式做到这一点有什么想法吗?

I have a list with some Belgian cities with diacritic characters: (Liège, Quiévrain, Franière, etc.) and I would like to transform these special characters to compare with a list containing the same names in upper case, but without the diacritical marks (LIEGE, QUIEVRAIN, FRANIERE)

What i first tried to do was to use the upper case:

LIEGE.contentEqual(Liège.toUpperCase()) but that doesn't fit because the Upper case of Liège is LIÈGE and not LIEGE.

I have some complicated ideas like replacing each character, but that sounds stupid and a long process.

Any ideas on how to do this in a smart way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

-黛色若梦 2024-09-15 15:26:17

从 Java 6 开始,您可以使用 java.text.Normalizer:

public String unaccent(String s) {
    String normalized = Normalizer.normalize(s, Normalizer.Form.NFD);
    return normalized.replaceAll("[^\\p{ASCII}]", "");
}

请注意,在 Java 5 中还有一个 sun.text.Normalizer,但强烈建议不要使用它,因为它是 Sun 专有 API 的一部分,并且已在 Java 6 中删除。

As of Java 6, you can use java.text.Normalizer:

public String unaccent(String s) {
    String normalized = Normalizer.normalize(s, Normalizer.Form.NFD);
    return normalized.replaceAll("[^\\p{ASCII}]", "");
}

Note that in Java 5 there is also a sun.text.Normalizer, but its use is strongly discouraged since it's part of Sun's proprietary API and has been removed in Java 6.

待"谢繁草 2024-09-15 15:26:17

在Java中查看这个方法

private static final String PLAIN_ASCII = "AaEeIiOoUu" // grave
            + "AaEeIiOoUuYy" // acute
            + "AaEeIiOoUuYy" // circumflex
            + "AaOoNn" // tilde
            + "AaEeIiOoUuYy" // umlaut
            + "Aa" // ring
            + "Cc" // cedilla
            + "OoUu" // double acute
    ;

    private static final String UNICODE = "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
            + "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
            + "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
            + "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
            + "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
            + "\u00C5\u00E5" + "\u00C7\u00E7" + "\u0150\u0151\u0170\u0171";

    /**
     * remove accented from a string and replace with ascii equivalent
     */
    public static String removeAccents(String s) {
        if (s == null)
            return null;
        StringBuilder sb = new StringBuilder(s.length());
        int n = s.length();
        int pos = -1;
        char c;
        boolean found = false;
        for (int i = 0; i < n; i++) {
            pos = -1;
            c = s.charAt(i);
            pos = (c <= 126) ? -1 : UNICODE.indexOf(c);
            if (pos > -1) {
                found = true;
                sb.append(PLAIN_ASCII.charAt(pos));
            } else {
                sb.append(c);
            }
        }
        if (!found) {
            return s;
        } else {
            return sb.toString();
        }
    }

Check out this method in Java

private static final String PLAIN_ASCII = "AaEeIiOoUu" // grave
            + "AaEeIiOoUuYy" // acute
            + "AaEeIiOoUuYy" // circumflex
            + "AaOoNn" // tilde
            + "AaEeIiOoUuYy" // umlaut
            + "Aa" // ring
            + "Cc" // cedilla
            + "OoUu" // double acute
    ;

    private static final String UNICODE = "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
            + "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
            + "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
            + "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
            + "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
            + "\u00C5\u00E5" + "\u00C7\u00E7" + "\u0150\u0151\u0170\u0171";

    /**
     * remove accented from a string and replace with ascii equivalent
     */
    public static String removeAccents(String s) {
        if (s == null)
            return null;
        StringBuilder sb = new StringBuilder(s.length());
        int n = s.length();
        int pos = -1;
        char c;
        boolean found = false;
        for (int i = 0; i < n; i++) {
            pos = -1;
            c = s.charAt(i);
            pos = (c <= 126) ? -1 : UNICODE.indexOf(c);
            if (pos > -1) {
                found = true;
                sb.append(PLAIN_ASCII.charAt(pos));
            } else {
                sb.append(c);
            }
        }
        if (!found) {
            return s;
        } else {
            return sb.toString();
        }
    }
才能让你更想念 2024-09-15 15:26:17

这是迄今为止我发现的最简单的解决方案,它在我们的应用程序中完美运行。

Normalizer.normalize(string, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); 

但我不知道Normalizer在Android平台上是否可用。

This is the simplest solution I've found so far and it works perfectly in our applications.

Normalizer.normalize(string, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); 

But I don't know if the Normalizer is available on the Android platform.

一个人的旅程 2024-09-15 15:26:17

如果您仍然需要 Android API 8 或更低版本(Android 2.2、Java 1.5),而您没有 Normalizer 类,这是我的代码,我认为修改比 Pentium10 答案更好:

public class StringAccentRemover {

    @SuppressWarnings("serial")
    private static final HashMap<Character, Character> accents  = new HashMap<Character, Character>(){
        {
            put('Ą', 'A');
            put('Ę', 'E');
            put('Ć', 'C');
            put('Ł', 'L');
            put('Ń', 'N');
            put('Ó', 'O');
            put('Ś', 'S');
            put('Ż', 'Z');
            put('Ź', 'Z');

            put('ą', 'a');
            put('ę', 'e');
            put('ć', 'c');
            put('ł', 'l');
            put('ń', 'n');
            put('ó', 'o');
            put('ś', 's');
            put('ż', 'z');
            put('ź', 'z');
        }
    };
    /**
     * remove accented from a string and replace with ascii equivalent
     */
    public static String removeAccents(String s) {
        char[] result = s.toCharArray();
        for(int i=0; i<result.length; i++) {
            Character replacement = accents.get(result[i]);
            if (replacement!=null) result[i] = replacement;
        }
        return new String(result);
    }

}

If you still need that for Android API 8 or lower (Android 2.2, Java 1.5) where you don't have Normalizer class, here's my code, I think better to modify than Pentium10 answer:

public class StringAccentRemover {

    @SuppressWarnings("serial")
    private static final HashMap<Character, Character> accents  = new HashMap<Character, Character>(){
        {
            put('Ą', 'A');
            put('Ę', 'E');
            put('Ć', 'C');
            put('Ł', 'L');
            put('Ń', 'N');
            put('Ó', 'O');
            put('Ś', 'S');
            put('Ż', 'Z');
            put('Ź', 'Z');

            put('ą', 'a');
            put('ę', 'e');
            put('ć', 'c');
            put('ł', 'l');
            put('ń', 'n');
            put('ó', 'o');
            put('ś', 's');
            put('ż', 'z');
            put('ź', 'z');
        }
    };
    /**
     * remove accented from a string and replace with ascii equivalent
     */
    public static String removeAccents(String s) {
        char[] result = s.toCharArray();
        for(int i=0; i<result.length; i++) {
            Character replacement = accents.get(result[i]);
            if (replacement!=null) result[i] = replacement;
        }
        return new String(result);
    }

}
夜深人未静 2024-09-15 15:26:17

Collat​​or 类是一种很好的方法(请参阅相应的 javadoc)。这是一个显示如何使用它的单元测试:

import static org.junit.Assert.assertEquals;

import java.text.Collator;
import java.util.Locale;

import org.junit.Test;

public class CollatorTest {
    @Test public void liege() throws Exception {
        Collator compareOperator = Collator.getInstance(Locale.FRENCH);
        compareOperator.setStrength(Collator.PRIMARY);

        assertEquals(0, compareOperator.compare("Liege", "Liege")); // no accent
        assertEquals(0, compareOperator.compare("Liège", "Liege")); // with accent
        assertEquals(0, compareOperator.compare("LIEGE", "Liege")); // case insensitive
        assertEquals(0, compareOperator.compare("LIEGE", "Liège")); // case insensitive with accent

        assertEquals(1, compareOperator.compare("Liege", "Bruxelles"));
        assertEquals(-1, compareOperator.compare("Bruxelles", "Liege"));
    }
}

编辑
很遗憾我的回答没有满足您的需求;也许是因为我将其作为单元测试呈现?这对你来说可以吗?我个人觉得它更好,因为它并且它使用SDK(不需要字符串替换)

Collator compareOperator = Collator.getInstance(Locale.FRENCH);
compareOperator.setStrength(Collator.PRIMARY);
if (compareOperator.compare("Liège", "Liege") == 0) {
    // if we are here, then it's the "same" String
}

希望这有帮助

The Collator class is a good way to do it (see corresponding javadoc). Here is a unit test that shows how to use it :

import static org.junit.Assert.assertEquals;

import java.text.Collator;
import java.util.Locale;

import org.junit.Test;

public class CollatorTest {
    @Test public void liege() throws Exception {
        Collator compareOperator = Collator.getInstance(Locale.FRENCH);
        compareOperator.setStrength(Collator.PRIMARY);

        assertEquals(0, compareOperator.compare("Liege", "Liege")); // no accent
        assertEquals(0, compareOperator.compare("Liège", "Liege")); // with accent
        assertEquals(0, compareOperator.compare("LIEGE", "Liege")); // case insensitive
        assertEquals(0, compareOperator.compare("LIEGE", "Liège")); // case insensitive with accent

        assertEquals(1, compareOperator.compare("Liege", "Bruxelles"));
        assertEquals(-1, compareOperator.compare("Bruxelles", "Liege"));
    }
}

EDIT :
sorry to see my answer did not meet your needs ; maybe it's beause I've presented it as unit test ? Is this ok for you ? I personnaly find it better because it's short and it uses the SDK (no need for String replacement)

Collator compareOperator = Collator.getInstance(Locale.FRENCH);
compareOperator.setStrength(Collator.PRIMARY);
if (compareOperator.compare("Liège", "Liege") == 0) {
    // if we are here, then it's the "same" String
}

hope this helps

魂ガ小子 2024-09-15 15:26:17

我不知道它是否在 Android 上可用,但在 JVM 上,您不应该在项目中重新实现它并重用已有的代码:只需使用 org.apache.commons.lang3.StringUtils#stripAccents

I don't know if it is avaible on Android but on the JVM, you should not reimplement it in your project and reuse already existing code: just use org.apache.commons.lang3.StringUtils#stripAccents

给不了的爱 2024-09-15 15:26:17

对于那些寻找干净的 java 解决方案的人,请使用 apache commons:

StringUtils.stripAccents("Liège").toUpperCase();

这将返回

LIEGE

For those looking for a clean java solution, use apache commons:

StringUtils.stripAccents("Liège").toUpperCase();

this will return

LIEGE
ぇ气 2024-09-15 15:26:17

由于 Froyo 或以前的 Android 版本不支持 Normalizer 类,我已合并此< /a> (我都投了赞成票),并对其进行了优化,获得了一些辅助方法。方法unaccentify只是将变音符号转换为普通字符,而方法slugify为输入字符串生成一个slug。希望它对某人有用。这是源代码:

import java.util.Arrays;
import java.util.Locale;  
import java.util.regex.Pattern;  

public class SlugFroyo {
    private static final Pattern STRANGE = Pattern.compile("[^a-zA-Z0-9-]");
    private static final Pattern WHITESPACE = Pattern.compile("[\\s]");

    private static final String DIACRITIC_CHARS = "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
            + "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
            + "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
            + "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
            + "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
            + "\u00C5\u00E5" + "\u00C7\u00E7" + "\u0150\u0151\u0170\u0171";

    private static final String PLAIN_CHARS = "AaEeIiOoUu" // grave
            + "AaEeIiOoUuYy" // acute
            + "AaEeIiOoUuYy" // circumflex
            + "AaOoNn" // tilde
            + "AaEeIiOoUuYy" // umlaut
            + "Aa" // ring
            + "Cc" // cedilla
            + "OoUu"; // double acute

    private static char[] lookup = new char[0x180];

    static {
        Arrays.fill(lookup, (char) 0);
        for (int i = 0; i < DIACRITIC_CHARS.length(); i++)
            lookup[DIACRITIC_CHARS.charAt(i)] = PLAIN_CHARS.charAt(i);
    }

    public static String slugify(String s) {
        String nowhitespace = WHITESPACE.matcher(s).replaceAll("-");
        String unaccented = unaccentify(nowhitespace);
        String slug = STRANGE.matcher(unaccented).replaceAll("");
        return slug.toLowerCase(Locale.ENGLISH);
    }

    public static String unaccentify(String s) {
        StringBuilder sb = new StringBuilder(s);
        for (int i = 0; i < sb.length(); i++) {
            char c = sb.charAt(i);
            if (c > 126 && c < lookup.length) {
                char replacement = lookup[c];
                if (replacement > 0)
                    sb.setCharAt(i, replacement);
            }
        }
        return sb.toString();
    }
}

Since class Normalizer is not supported in Froyo or previous Android versions, I have combined this and this (which I both voted up), and optimized it, obtaining a couple of helper methods. Method unaccentify simply converts diacritic chars to plain chars, while method slugify generates a slug for the input string. Hope it can be useful to someone. Here is the source code:

import java.util.Arrays;
import java.util.Locale;  
import java.util.regex.Pattern;  

public class SlugFroyo {
    private static final Pattern STRANGE = Pattern.compile("[^a-zA-Z0-9-]");
    private static final Pattern WHITESPACE = Pattern.compile("[\\s]");

    private static final String DIACRITIC_CHARS = "\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
            + "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
            + "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
            + "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
            + "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
            + "\u00C5\u00E5" + "\u00C7\u00E7" + "\u0150\u0151\u0170\u0171";

    private static final String PLAIN_CHARS = "AaEeIiOoUu" // grave
            + "AaEeIiOoUuYy" // acute
            + "AaEeIiOoUuYy" // circumflex
            + "AaOoNn" // tilde
            + "AaEeIiOoUuYy" // umlaut
            + "Aa" // ring
            + "Cc" // cedilla
            + "OoUu"; // double acute

    private static char[] lookup = new char[0x180];

    static {
        Arrays.fill(lookup, (char) 0);
        for (int i = 0; i < DIACRITIC_CHARS.length(); i++)
            lookup[DIACRITIC_CHARS.charAt(i)] = PLAIN_CHARS.charAt(i);
    }

    public static String slugify(String s) {
        String nowhitespace = WHITESPACE.matcher(s).replaceAll("-");
        String unaccented = unaccentify(nowhitespace);
        String slug = STRANGE.matcher(unaccented).replaceAll("");
        return slug.toLowerCase(Locale.ENGLISH);
    }

    public static String unaccentify(String s) {
        StringBuilder sb = new StringBuilder(s);
        for (int i = 0; i < sb.length(); i++) {
            char c = sb.charAt(i);
            if (c > 126 && c < lookup.length) {
                char replacement = lookup[c];
                if (replacement > 0)
                    sb.setCharAt(i, replacement);
            }
        }
        return sb.toString();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文