从文件创建字典

时间:2013-11-22 02:51:36

标签: python-3.x

我正在创建一个代码,允许用户输入他们选择的.txt文件。因此,例如,如果文本为:

“我是你。你是我。”

我希望我的代码能够创建一个类似于此的字典:
{我:2,上午:1,你:2,是:1}

将文件中的单词显示为键,将次数显示为值。资本化应该是无关紧要的,所以= ARE = ArE = arE = etc ......

到目前为止,这是我的代码。有什么建议/帮助吗?

>> file = input("\n Please select a file")
>> name = open(file, 'r')    
>> dictionary = {}
>> with name:
     >> for line in name:
          >> (key, val) = line.split()
          >> dictionary[int(key)] = val

1 个答案:

答案 0 :(得分:1)

看看这个答案中的例子:

Python : List of dict, if exists increment a dict value, if not append a new dict

您可以使用collections.Counter()轻松地执行您想要的操作,但如果由于某种原因您无法使用它,您可以使用defaultdict甚至是一个简单的循环来构建您想要的字典

以下是解决问题的代码。这将适用于Python 3.1及更高版本。

from collections import Counter
import string

def filter_punctuation(s):
    return ''.join(ch if ch not in string.punctuation else ' ' for ch in s)

def lower_case_words(f):
    for line in f:
        line = filter_punctuation(line)
        for word in line.split():
            yield word.lower()

def count_key(tup):
    """
    key function to make a count dictionary sort into descending order
    by count, then case-insensitive word order when counts are the same.
    tup must be a tuple in the form: (word, count)
    """
    word, count = tup
    return (-count, word.lower())

dictionary = {}

fname = input("\nPlease enter a file name: ")
with open(fname, "rt") as f:
    dictionary = Counter(lower_case_words(f))

print(sorted(dictionary.items(), key=count_key))

从你的例子我可以看出你想要删除标点符号。由于我们要将字符串拆分为空白区域,因此我编写了一个将标点符号过滤到空白区域的函数。这样,如果你有一个像hello,world这样的字符串,当我们在空格上分割时,这将被分成单词helloworld

函数lower_case_words()是一个生成器,它一次读取一行输入文件,然后从每行产生一个单词。这整齐地将我们的输入处理放入一个整洁的“黑匣子”中,稍后我们可以简单地调用Counter(lower_case_words(f))并为我们做正确的事。

当然你不必打印排序的字典,但我认为这样看起来更好。我将排序顺序放在最高位,并且计数相等,按字母顺序排列。

根据建议的输入,这是结果输出:

[('i', 2), ('you', 2), ('am', 1), ('are', 1)]

由于排序,它总是按上述顺序打印。