【问题标题】:In python, extracting non-English words在python中,提取非英语单词
【发布时间】:2014-04-02 02:32:29
【问题描述】:

我有一个包含英文字符和其他语言字符的文本文件。 并使用下面的代码,我想从这个文件中提取一些不是英文的单词 特别是韩语(Unicode 范围从 UTF-8 中的 AC00 到 D7AF)

有没有办法在这段代码中做到这一点??

我需要做点别的吗?

....
text = f.read()
words = re.findall(r'\w+', dataString)
f.close()
....

【问题讨论】:

    标签: python unicode


    【解决方案1】:

    使用大写\W = 匹配-字母数字字符,排除 _

    >>> re.findall('[\W]+', u"# @, --►(Q1)-grijesh--b----►((Qf)), ");
    [u'# @, --\u25ba(', u')-', u'--', u'----\u25ba((', u')), ']
    

    来自:Unicode HOWTO? 要读取 unicode 文本文件,请使用:

    import codecs
    f = codecs.open('unicode.rst', encoding='utf-8')
    for l in f:
      # regex code here 
    

    我有一个文件:

    :~$ cat file
    # @, --►(Q1)-grijesh--b----►((Qf)),
    

    从 Python 中读取:

    >>> import re
    >>> import codecs
    >>> f = codecs.open('file', encoding='utf-8')
    >>> for l in f:
    ...  print re.findall('[\W]+', l)
    ... 
    [u'# @, --\u25ba(', u')-', u'--', u'----\u25ba((', u')),\n']
    >>> 
    

    要阅读字母单词,请尝试

    >>> f = codecs.open('file', encoding='utf-8')
    >>> for l in f:
    ...  print re.findall('[^\W]+', l)
    ... 
    [u'Q1', u'grijesh', u'b', u'Qf']
    

    注意:小号\w 匹配一个字母数字字符,包括 _

    【讨论】:

      【解决方案2】:

      要查找从 AC00 到 D7AF 范围内的所有字符:

      import re
      
      L = re.findall(u'[\uac00-\ud7af]+', data.decode('utf-8'))
      

      要查找所有非 ascii 单词:

      import re
      
      def isascii(word):
          return all(ord(c) < 128 for c in word)
      
      words = re.findall(u'\w+', data.decode('utf-8'))
      non_ascii_words = [w for w in words if not isascii(w)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-19
        • 2013-09-17
        • 1970-01-01
        • 2011-07-20
        • 2019-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多