字典python麻烦

时间:2014-05-24 00:18:18

标签: python

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

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}}

1 个答案:

答案 0 :(得分: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

file:cats.txt

cat1.txt
cat2.txt

file:cat1.txt

whiskey
sugar syrup

file:cat2.txt

whiskey

示例运行:

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