2014-05-24 224 views
-2

好的,如果我有一个存储为sys.argv [1]的文件,这个文件只有3行,每行包含一个.txt文件的名称,然后它包含一个猫品种的列表。我想打开sys.argv [1],然后系统地打开与每行sys.argv [1]关联的每个文本文件。对于每个文本文件,我想创建一个字典,统计每个品种被列出的次数。最后,我想要一个包含所有这些单独字典的字典,其中每个字典的键都是其名称,如sys.argv [1]文件中所列。这里是我的尝试:字典python麻烦

f = open(sys.argv[1], 'r') 
all_cats = {} 
for line in f: 
    w = open(line, 'r') 
    cat_count = {} 
    for line in w: 
     line = line.lower() 
     for mark in string.punctuation: 
      if mark in line: 
       line = line.replace(mark, '') 
     line = line.split() 
     for cat in line: 
      if word not in cat_count: 
       cat_count[cat] = 1 
      else: 
       cat_count[cat] += 1 
     all_cats[line] = cat_count 
    w.close() 
f.close() 

我的预期了认沽将

{'catdictionary#1.txt' : {'long hair': 0, 'short hair' : 1} 'cat dictionary#2.txt' : {'long hair' : 1, 'short hair' : 0}} 
+0

我会把'w = open(line,'r')'改成'w = open(line.rstrip(),'r')'。 –

+0

发布_minimal_工作示例,或者人们将继续投票。 – DanielSank

+0

我不能让一个例子工作是问题 – user3670651

回答

1

你可以尝试这样的事情。它为每个“cat文件”使用专门的Counter类。对于我的样本数据我有饮料配方:)

#!/usr/bin/env python 

import re, sys 
from collections import Counter 


file_count = dict() 
filenames = [ name.strip() for name in open(sys.argv[1]) ] 

for name in filenames: 
    for line in open(name): 
     cat_count = Counter() 
     for cat in re.sub('[^a-zA-Z ]+', '', line.rstrip()).split(): 
      cat_count[cat] += 1 
     file_count[name] = cat_count 

print file_count 

文件:cats.txt

cat1.txt 
cat2.txt 

文件:cat1.txt

whiskey 
sugar syrup 

文件:cat2.txt

whiskey 

样品运行:

./countcats.py cats.txt 
{'cat1.txt': Counter({'syrup': 1, 'sugar': 1}), 'cat2.txt': Counter({'whiskey': 1})}