# 计算不重复字数[重复]Counting the number of unique words [duplicate]

``````text = "There is one handsome boy. The boy has now grown up. He is no longer a boy now."
print len(set(w.lower() for w in text.split()))
``````

## 4 个回复4

### ===============>>#1 票数：2

``````import re
print len(re.findall('\w+', text))
``````

``````print len(set(re.findall('\w+', text.lower())))
``````

### ===============>>#2 票数：1

``````In [65]: text = "There is one handsome boy. The boy has now grown up. He is no longer a boy now."

In [66]: import re

In [68]: set(m.group(0).lower() for m in re.finditer(r"\w+",text))

Out[68]:
set(['grown',
'boy',
'he',
'now',
'longer',
'no',
'is',
'there',
'up',
'one',
'a',
'the',
'has',
'handsome'])
``````

### ===============>>#3 票数：1

``````text = "There is one handsome boy. The boy has now grown up. He is no longer a boy now."
punc_char= ",.?!'"
for letter in text:
if letter == '"' or letter in punc_char:
text= text.replace(letter, '')
text= set(text.split())
len(text)
``````

### ===============>>#4 票数：0

``````import re
words = re.findall('\w+', text)
``````

``````cwords = {}
for word in words:
try:
cwords[word] += 1
except KeyError:
cwords[word] = 1
``````

``````len(cwords)
``````