繁体   English   中英

将文本文件转换为字典

[英]Convert Text File to Dictionary

假设我想在 Pycharm (keywords.txt) 中打开一个文本文件,假设这个文本文件包含一个单词列表,带有相应的数值,因此文本文件的格式如下:

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

(数值范围为 1-10)

我知道为了打开这个文件(以读取模式),我们将执行以下操作:

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

我如何读取文本文件每一行上的每个单词,然后将其作为关键字存储到字典中,然后还存储其对应的数值?

例如:

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

我试过的:

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)

我真的不知道我要去哪里...

它只是打印一堆以下内容:

{'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

这个作品通过打开文件,用删除空白strip()使用,分裂琴弦成列表strip()然后设置键的字符串数组的第一部分s ,这是水果,并且该值到第二部分将其转换为int

您可以使用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(', ') 获取该行中第一项和第二项的列表,然后您可以将这两个字符串存储在字典中,您可以如有必要,将第二个字符串转换为整数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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