首页 > 关于统计某一个 单词 在 文本中 出现的次数

关于统计某一个 单词 在 文本中 出现的次数

人生苦短,我用Python.用了不会,来到segment.
我是一个python 初学者,想要实现一个“模块”,可以让用户输入某个单词,然后就可以得到它在文本中出现的次数。
试了一个下午,但由于自学,有些地方自己不是很懂,在google上,以及http://stackoverflow.com/ 上,没有找到适合自己的答案。(大多都是统计所有单词的次数,以及有些局部的函数自己不是很明白) 所以,把自己想法写想法,请教一下大家,如何写这样一个模块。

我想要实现的效果
让用户输入:

input the word: love

输出结果:

love was found 520 times

1.这是自己写的一个程序,运行错误,但不知道怎么改?

import re
def count_unique_word(filename):

    word = input ("Input the word:")
    for word in open(filename).read().split():
        count = len (re.findall (word,'sketch.txt'))
        print "%s was found %d times" % (word, count)

运行结果:

>>> import os
>>> os.chdir('/Users/apple/Desktop/Python/chapter')
>>> import re
>>> def count_unique_word(filename):
...     
...     word = input ("Input the word:")
...     for word in open(filename).read().split():
...         count = len (re.findall (word,'sketch.txt'))
...         print "%s was found %d times" % (word, count)
... 
>>> count_unique_word('sketch.txt')
Input the word:the
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in count_unique_word
  File "<string>", line 1, in <module>
NameError: name 'the' is not defined
>>>
```` 

自己猜想: 是不是 input 写的有问题?(但是我不知道怎么改)

NameError: name 'the' is not defined

---

###2.于是我又尝试了不用正则表达式的方法,但还是有问题。###

import os
os.chdir('/Users/apple/Desktop/Python/chapter')

f = open('sketch.txt')

word = input("please input the word")
total = 0
for line in f:
if word in line:
total += 1
f.close()
print total



File "/Users/apple/Desktop/Python/chapter/unique_words4.py", line 22, in
word = input ("Input the word:")
File "", line 1, in
NameError: name 'the' is not defined


--- ###3.最后推而求其次,简化成如下。### ```python import os os.chdir('/Users/apple/Desktop/Python/chapter') f = open('sketch.txt') total = 0 for line in f: if "the" in line: total += 1 f.close() print total

运行结果

applematoMacBook-Pro-3:~ apple$ python /Users/apple/Desktop/Python/chapter/unique_words4.py
21

结果出来,感觉”热泪盈眶“,终于有一个结果了。
但这离我想要的效果,还有一段距离。


这是我以前用java写的一个查找的方法 你可以看看 虽然不是python写的 但编程最重要的就是思路 看看能不能对你有帮助


有很多问题。

首先,Python 3 和 Python 2 是不同的。在 Python 3 中 input() 是让用户输入一行文本,Python 2 中却除了输入之外还会对它进行求值(eval)。你好像在使用 Python 2,那么你应该使用 raw_input()

其次,你不应该这样用正则。如果要找特定的字符串,使用普通的字符串查找就可以了。

最后,你的代码逻辑是错的。两段代码都是错的(那段没有格式化的代码没法看,所以我忽略掉了)。

import os
os.chdir('/Users/apple/Desktop/Python/chapter')

word = raw_input('Input your world: ').strip()
count = 0
with open('sketch.txt') as f:
  for line in f:
    count += f.split().count(word)
print count
【热门文章】
【热门文章】