2013-03-20 75 views
-2

我有一個叫做dogs.txt的文本文件,內容如下。如何計算Python中的文本文件中出現兩個單詞的次數?

'#' 色體皮毛類型

白色大硬盤保守

黃色大硬盤保守

褐色大的軟暴力

黃色寬大柔軟的保守

棕色小硬保守

褐色小而硬的保守

白色小而硬的保守

黃色小軟暴力

黃色小硬暴力

棕色的大硬盤保守

白色寬大柔軟的保守

黃色小軟暴力

褐色小軟保守

棕色的大硬暴力

褐色小而硬的保守

黃色小硬暴力

每一行代表一個狗。當輸入dogs.txt時,我希望輸出顯示兩件事情。

  1. 有多少隻狗?檢查

  2. 有多少隻狗是黃色和暴力的?

輸出會告訴你有16只狗。

接下來我需要做的是找出這16只狗中有多少隻是黃色和暴力的。我一直在堅持如何做到這一點。我想我將不得不使用infile.read(),但我不知道如何。請幫助傢伙。

+1

是否使用line.strip()檢查,如果該行是空的? – 2013-03-20 00:32:44

+0

@Adam Obeng是的我正在使用line.strip()來檢查行是否爲空 – Jett 2013-03-20 00:37:48

+0

您的代碼的問題是'num_yellow_and_violent = + 1'。這'= + 1'意味着「變量的值設置爲'+ 1'。你想'+ = 1'。 – abarnert 2013-03-20 01:13:18

回答

1
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 

一些事情:

  • ,而不是設置一個變量不分析的文件,如果無法找到,你可以提出一個自定義異常
  • 你不應該使用的類名作爲變量名稱(例如file

其中給出:

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) 
+0

您yellow_and_violent答案給0每次。 – Jett 2013-03-20 00:36:03

+0

應該是'yellow_and_violent + = 1',在倒數第二行。此外,你有一個額外'''在你的'if' – nbrooks 2013-03-20 00:44:50

+0

@nbrooks,謝謝。這就是爲什麼我不喜歡的增量運營結束。 – 2013-03-20 00:47:09

1

使用正則表達式:

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) 
+0

正則表達式,嚴重? – kay 2013-03-20 00:32:46

+0

@Kay,你能否詳細說明你的評論? – perreal 2013-03-20 00:34:16

+0

這個問題很微不足道。我只會推薦正則表達式作爲最後的手段。這不是一個問題,你應該使用正則表達式... – kay 2013-03-20 00:35:40

2

這裏是一個快速的方法來檢查是黃色和暴力的數量:

with open('dogs.txt') as f: 
    f.readline() # Skip first line 
    print sum({'yellow','violent'}.issubset(line.split()) for line in f) 

但是,當我添加行號檢查它不是eleg螞蟻

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 
0
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) 
相關問題