在Python中,如何计算两个单词在文本文件中出现的次数?
我有一个名为dogs.txt的文本文件,其中有以下几行 “#”颜色身体毛发类型 白色大硬壳 黄色大硬壳 棕色大而柔软 黄色大的软的 棕色小硬保守 棕色小硬保守 白色小硬壳 黄色小而软 黄色小而硬 棕色大硬壳 白色大号软包装 黄色小而软 棕色小而柔软 棕色大而硬 棕色小硬保守 黄色小而硬 每条线代表一只狗。当用户输入dogs.txt时,我希望输出显示两件事在Python中,如何计算两个单词在文本文件中出现的次数?,python,file,text,count,Python,File,Text,Count,我有一个名为dogs.txt的文本文件,其中有以下几行 “#”颜色身体毛发类型 白色大硬壳 黄色大硬壳 棕色大而柔软 黄色大的软的 棕色小硬保守 棕色小硬保守 白色小硬壳 黄色小而软 黄色小而硬 棕色大硬壳 白色大号软包装 黄色小而软 棕色小而柔软 棕色大而硬 棕色小硬保守 黄色小而硬 每条线代表一只狗。当用户输入dogs.txt时,我希望输出显示两件事 有多少只狗?检查 有多少只狗是黄色和暴力的 输出将告诉您有16只狗 接下来我要做的是找出这16只狗中有多少是黄色的和暴力的。我被困在如何做这件
yellow_and_violent = 0
for line in infile:
if line.strip() and line[0]!='#':
lines+=1
if ('yellow' in line) and ('violent' in line'):
yellow_and_violent += 1
还有几件事:
- 如果找不到文件,可以引发自定义异常,而不是将变量设置为不分析文件
- 不应将类名用作变量名(例如
)文件
import os.path
filename = input("Enter name of input file >")
try:
infile = open(filename, "r")
except IOError:
raise Exception("Error opening file '%s', analysis will not continue" % filename)
dogs = 0
yellow_and_violent = 0
for line in infile:
if line.strip() and line[0]!='#':
dogs += 1
if ('yellow' in line) and ('violent' in line):
yellow_and_violent += 1
print("Total dogs =",dogs)
print("Yellow and violent dogs = ", yellow_and_violent)
使用正则表达式:
import os.path
import sys
import re
reg = re.compile("^yellow.*violent")
try:
file=sys.argv[1]
infile=open(file,"r")
except IOError:
raise Exception("open '%s' failed" % filename)
lines=0
yv=0
for line in infile:
if line.strip() and line[0]!='#':
lines+=1
if reg.match(line):
yv+=1
print("Total dogs =",lines)
print("Total yv dogs =",yv)
下面是一种快速检查黄色暴力数字的方法:
with open('dogs.txt') as f:
f.readline() # Skip first line
print sum({'yellow','violent'}.issubset(line.split()) for line in f)
但是,当我添加行号检查时,它就没有那么优雅了
with open('dogs.txt') as f:
f.readline() # Skip first line
i, num_dogs = 0, 0
for line in f:
num_dogs += {'yellow','violent'}.issubset(line.split())
i += 1
print i, num_dogs
您是否使用line.strip()检查行是否为空?@Adam Obeng是的,我使用line.strip()检查行是否为空代码的问题是
num\u yellow\u和+1
。=+1
表示将变量设置为值+1
。您需要+=1
@abarnert非常感谢。这就是我们所缺少的:)@Kay,你能详细解释一下你的评论吗?这个问题很琐碎。我只建议把正则表达式作为最后的手段。这不是一个问题,你应该使用正则表达式…为什么?它们速度慢吗?我在file=sys.argv[1]中使用这个程序时出错,说列表索引超出了范围range@Jett,是的,您需要指定一个文件名:python sc.py input
您的黄色\u和\u暴力答案每次都给出0。应该是yellow\u和\u暴力+=1
,在倒数第二行。另外,如果您的@nbrooks,您的末尾还有一个额外的'
,谢谢。这就是我不喜欢递增运算符的原因。它是黄色的\u和\u暴力+=1,我去掉了'out',但它仍然给16只狗,但它总是打印0黄色和暴力。@Jett:在infle
循环中,应该只有一行,因为一旦你遍历了文件对象一次,就没有行了
dog_counter = 0
yellow_and_violent = 0
with open('dog.txt', 'r') as fd:
for line in fd.readlines():
if line.startswith("'#'") or (not line.strip()):
continue
dog_counter += 1
if ('yellow' in line) and ('violent' in line):
yellow_and_violent += 1
print("Total dogs: %d" % dog_counter)
print("yellow and violent dogs: %d" % yellow_and_violent)