简体   繁体   中英

Convert Text File to Dictionary

Let's say I want to open a text file within Pycharm (keywords.txt), and lets say this text file contained a list of words, with corresponding numerical values, thus the text file was of the following form:

apple, 3
banana, 5 
happy, 7
tiger, 9

(with numerical values ranging from 1-10)

I understand that in order to open this file(in read mode), we would do the following:

with open('keywords.txt','r') as f:

How could I read over each individual word, on each line of the text file, and then store it into a dictionary as a keyword, and then also store its corresponding numerical value?

For example:

dictionary = {'apple':'3','banana':'5','happy':'7','tiger':'9'}

What I tried:

with open('keywords.txt','r') as k:
    size_to_read = 1
    k_text = k.read(size_to_read)
    while len(k_text) > 0:
            if k_text.isalpha:
                keywordic = dict.fromkeys({'k_text'})
                print(keywordic)
            k_text = k.read(size_to_read)

I didn't really know where I was going with this...

It just prints a bunch of the following:

{'k_text': None}
def readFile(filename):
    # Dict that will contain keys and values
    dictionary =  {}
    with open(filename, "r") as f:
        for line in f:
            s = line.strip().split(", ")
            dictionary[s[0]] = int(s[1])
        return dictionary

This works by opening the file, removing whitespace with strip() , splitting the strings into lists using strip() and then setting the key to the first part of the string array s , which is the fruit, and the value to the second part after casting it to an int .

You can iterate over a file line by line using for line in myfile: .

dictionary = {}
with open("keywords.txt", "r") as file:
    for line in file:
        key, value = line.strip().split(",")
        dictionary[key] = value
print(dictionary)
data_dict = { line.split(",")[0] : line.split(",")[1] for line in open('keywords.txt') }

只需逐行读取文件,并且对于每一行字符串,使用`split(', ') 获取该行中第一项和第二项的列表,然后您可以将这两个字符串存储在字典中,您可以如有必要,将第二个字符串转换为整数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM