检测单词中的重音(Python)

时间:2014-02-18 03:50:08

标签: python regex unicode command-line non-ascii-characters

这是故事:我编写了一个程序,可以找到字典中的所有算法类。但是,我在处理重音字符时遇到问题。目前我的代码读入它们,将它们看作是不可见的,但仍然以“\ xc3 \ ???”的形式打印出某种替换代码。我想丢弃带有重音的所有单词,但我不知道如何检测它们。

我尝试过的事情:

  • 检查类型是否为unicode
  • 使用正则表达式检查包含'\ xc3'
  • 的单词
  • 解码/编码(我完全不了解unicode,但无论我尝试什么都不起作用)。

问题/问题:我需要找出如何检测重音,但我的程序会将重音打印到命令行上,就像奇怪的'\ xc3 \ ???'字符,这不是程序如何对待它们,因为我找不到任何包含'\ xc3 \ ???'的单词尽管被打印到命令行。

示例:sé - > s \ xc3 \ xa9,sé和s被我的程序视为字谜。

测试字典:

stop
tops
pots
hello
world
pit
tip
\xc3\xa9
sé
s
se

代码输出:

Found
\xc3\xa9
['pit', 'tip']
['world']
['s\xc3\xa9', 's']
['\\xc3\\xa9']
['stop', 'tops', 'pots']
['se']
['hello']

编程本身:

import re

anadict = {};

for line in open('fakedic.txt'):#/usr/share/dict/words'):
        word = line.strip().lower().replace("'", "")
        line = ''.join(sorted(ch for ch in word if word if ch.isalnum($
        if isinstance(word, unicode):
                print word
                print "UNICODE!"
        pattern = re.compile(r'xc3')
        if pattern.findall(word):
               print 'Found'
               print word
        if anadict.has_key(line):
                if not (word in anadict[line]):
                        anadict[line].append(word)
        else:
                anadict[line] = [word]

for key in anadict:
        if (len(anadict[key]) >= 1):
                print anadict[key]

帮助?

2 个答案:

答案 0 :(得分:1)

所以基本上抓住我的答​​案......看看这里:

How to check if a string in Python is in ASCII?

要点是你可以检查每个字符以查看字符的ord是否小于128,这样可以检查它是否是重音字符。或者你可以做很多尝试和捕捉,寻找在重音字符期间抛出的unicode错误。 (后者似乎更有效的答案)

这对我来说绝对是一次学习经历:)抱歉这么久

答案 1 :(得分:1)

我最终使用正则表达式(基本上用于检查不是字母字符的所有内容):

if re.match('^[a-zA-Z_]+$', word):

这帮助我删除了任何带有\或任何其他数字或时髦符号的单词。不是一个完美的解决方案,但它确实有效。