关于统计某一个 单词 在 文本中 出现的次数
人生苦短,我用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 "", line 1, in
File "", line 3, in count_unique_word
File "", line 1, in
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
结果出来,感觉”热泪盈眶“,终于有一个结果了。
但这离我想要的效果,还有一段距离。
相关阅读:
css 中引入cssPie兼容IE8的圆角没有起任何作用?
如何获取id_of_setinterval?
jQuery ajax success()括号里的参数是什么?
如图所示;我点击按钮后,列表显示,我点击其他任意位置,列表消失,这个这么做?
在Apache中如何配置既可以使用虚拟主机又可以使用localhost访问不是虚拟主机的项目
flask 上传的文件只能放在项目的根目录下么?
背景图既要清晰,又要加载速度快,有什么折衷的方法吗?
tmpnam 为什么不安全
性能(压力)测试单台电脑能模拟多少并发?
js全局变量
Error:(1, 0) Plugin with id 'com.android.application' not found.
怎样在app关闭的情况下,接受推送消息?
为什么闭包可以解决js中循环绑定事件的问题?
求推荐漏洞扫描和注入攻击的工具
mongodb数据结构设计及多维数组嵌套文档的查询
node 如何在文件数据上传完毕之前,获取文件的元数据
解说一下php函数localeconv的所对应的每个健名的含义?
setTimeout 0秒问题;
react-router中,IndexRoute为什么不自动加载Home组件?
Android应用如何加载framework的Class到自己的JVM?应用JVM与Zygote JVM是什么关系?