找到带有英文单词和中文字符的句子长度

时间:2013-05-13 17:44:49

标签: python

句子可以包括非英文字符,例如中国:

你好,hello world

长度的预期值为5(2个汉字,2个英文单词和1个逗号)

3 个答案:

答案 0 :(得分:2)

您可以使用大多数中文字符位于unicode范围0x4e00 - 0x9fcc

# -*- coding: utf-8 -*-
import re

s = '你好 hello, world'
s = s.decode('utf-8')

# First find all 'normal' words and interpunction
# '[\x21-\x2f]' includes most interpunction, change it to ',' if you only need to match a comma
count = len(re.findall(r'\w+|[\x21-\x2]', s))

for word in s:
    for ch in word:
        # see https://stackoverflow.com/a/11415841/1248554 for additional ranges if needed
        if 0x4e00 < ord(ch) < 0x9fcc:
            count += 1

print count

答案 1 :(得分:1)

如果您乐意将每个中文字符视为一个单独的单词,即使情况并非总是如此,您可以通过使用{{3}检查每个字符的Unicode字符属性来完成类似的操作。 }。

例如,如果您在示例文本上运行此代码:

# -*- coding: utf-8 -*-

import unicodedata

s = u"你好,hello world"     
for c in s:
  print unicodedata.category(c)

您会看到中文字符报告为Lo(字母其他),这与拉丁字符不同,后者通常会报告为LlLu

知道这一点,您可以将Lo的任何内容视为单个单词,即使它没有用空格/标点符号分隔。

现在这几乎肯定不适用于所有语言的所有情况,但它可能足以满足您的需求。

<强>更新

以下是一个更完整的示例,说明如何做到这一点:

# -*- coding: utf-8 -*-

import unicodedata

s = u"你好,hello world"     

wordcount = 0
start = True
for c in s:      
  cat = unicodedata.category(c)
  if cat == 'Lo':        # Letter, other
    wordcount += 1       # each letter counted as a word
    start = True                       
  elif cat[0] == 'P':    # Some kind of punctuation
    wordcount += 1       # each punctation counted as a word
    start = True                       
  elif cat[0] == 'Z':    # Some kind of separator
    start = True
  else:                  # Everything else
    if start:
      wordcount += 1     # Only count at the start
    start = False    

print wordcount    

答案 2 :(得分:0)

这里的逻辑存在问题:

你好
,

这些都是字符,而不是单词。对于汉字,您需要做一些事情possibly with regex

这里的问题是汉字可能是单词部分或单词。

大好

在正则表达式中,是一两个字?每个角色本身就是一个单词,但它们也是一个单词。

hello world

如果你在空格上算这个,那么你会得到2个单词,但你的中文正则表达式也可能不起作用。

我认为你能用“单词”来完成这项工作的唯一方法就是分别编写中文和英文。

相关问题