功能:
统计一个纯英文文本文件中的单词出现频次
代码:
#coding:utf-8 import re from collections import Counter def word_count(txt): word_pattern = r'[a-zA-Z]+' words = re.findall(word_pattern,txt) return Counter(words).items() if __name__ == "__main__": txt = open('test.txt','r').read().lower() print(word_count(txt))
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#coding:utf-8
import
re
from
collections
import
Counter
def
word_count
(
txt
)
:
word_pattern
=
r
'[a-zA-Z]+'
words
=
re
.
findall
(
word_pattern
,
txt
)
return
Counter
(
words
)
.
items
(
)
if
__name__
==
"__main__"
:
txt
=
open
(
'test.txt'
,
'r'
)
.
read
(
)
.
lower
(
)
print
(
word_count
(
txt
)
)
|
测试文件内容:
Henry was a pen name used by an American writer of short stories. His real name was William Sydney Porter. He was born in North Carolina in 1862. As a young boy he lived an exciting life. He did not go to school for very long, but he managed to teach himself everything he needed to know. When he was about 20 years old, O. Henry went to Texas, where he tried different jobs. He first worked on a newspaper, and then had a job in a bank, when some money went missing from the bank O. Henry was believed to have stolen it. Because of that, he was sent to prison. During the three years in prison, he learned to write short stories. After he got out of prison, he went to New York and continued writing. He wrote mostly about New York and the life of the poor there. People liked his stories, because simple as the tales were, they would finish with a sudden change at the end, to the reader¡¯s surprise.
1
|
Henry
was
a
pen
name
used
by
an
American
writer
of
short
stories
.
His
real
name
was
William
Sydney
Porter
.
He
was
born
in
North
Carolina
in
1862.
As
a
young
boy
he
lived
an
exciting
life
.
He
did
not
go
to
school
for
very
long
,
but
he
managed
to
teach
himself
everything
he
needed
to
know
.
When
he
was
about
20
years
old
,
O
.
Henry
went
to
Texas
,
where
he
tried
different
jobs
.
He
first
worked
on
a
newspaper
,
and
then
had
a
job
in
a
bank
,
when
some
money
went
missing
from
the
bank
O
.
Henry
was
believed
to
have
stolen
it
.
Because
of
that
,
he
was
sent
to
prison
.
During
the
three
years
in
prison
,
he
learned
to
write
short
stories
.
After
he
got
out
of
prison
,
he
went
to
New
York
and
continued
writing
.
He
wrote
mostly
about
New
York
and
the
life
of
the
poor
there
.
People
liked
his
stories
,
because
simple
as
the
tales
were
,
they
would
finish
with
a
sudden
change
at
the
end
,
to
the
reader¡¯
s
surprise
.
|
脚本参考参考地址:脚本地址