python中读取txt文件、统计其中所有字母出现的频度_使用python统计目标词在文件中出频度的实现方法...

本文是一位Python初学者在尝试编写统计文本中特定单词出现次数的程序时遇到的问题及尝试的三种方法。第一种使用正则表达式,第二种尝试不使用正则表达式,第三种简化版的尝试。作者指出代码中存在的错误,包括Python 2和3的input()差异,以及正则表达式的误用,并给出正确逻辑的代码示例。
摘要由CSDN通过智能技术生成

人生苦短,我用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

结果出来,感觉”热泪盈眶“,终于有一个结果了。

但这离我想要的效果,还有一段距离。

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

531f2e899f47c6ddeb105f41f66b2bc1.png

有很多问题。

首先,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

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd19588.html

相关文章 Recommend

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值