【问题标题】:function saving words as keys [closed]将单词保存为键的功能[关闭]
【发布时间】:2019-11-17 10:44:03
【问题描述】:

我正在尝试编写一个函数来读取 .txt 文件中包含的单词并将它们作为键写入字典中。该值可以是任何值。该程序应该允许我使用 in 运算符来检查字符串是否在字典中。

我尝试过这样的事情:

words = open('words.txt')
def k():
    for word in words:
        key = word[0]

print(k)

我不知道该怎么做。谁能帮帮我?

【问题讨论】:

  • 这些键的值应该是什么?
  • python 中没有values 的dictionary 称为set。您可以通过以下方式轻松创建它:words_set = set(words)
  • 字典不只是键,它们包含键和值对,您可以编辑您的问题以给出预期输出的示例吗?
  • 值可以是任意的
  • 另外,您提供的代码表明您可能不知道如何调用函数、如何从函数返回值、如何读取文件以及究竟什么是字典。我强烈建议回到 python 的基础

标签: python python-3.x dictionary pycharm key


【解决方案1】:

file=open("C:/Users/sghungurde/Documents/love.txt")

def k():

    dict={}

    for word in file.read().split():

        key=word

    #print(word)

        dict[key]='null'

    return dict


print(k())

【讨论】:

    【解决方案2】:

    变量词实际上就是你的词。没有必要将索引设为 0。

    words = open('words.txt')
    def k():
        keys = []
        for word in words:
            keys.append(word)
        return keys
    

    【讨论】:

      【解决方案3】:

      我认为您想读取文件并遍历其行并保存每行的第一个单词。 with open 语法比直接打开文件更好,因为 this 原因。试试这个代码:

      with open('words.txt') as f:
        words=f.read()
        keys=[]
        for word in words:
          keys.append(word[0])
        print(keys)
      

      【讨论】:

        【解决方案4】:
        with open('words.txt') as f:
          words = f.read()
          keys = set(words)
        
        if "apple" in keys:
          pass
        
        if "orange" in keys:
          pass
        
        if "pear" in keys:
          pass
        

        【讨论】:

          【解决方案5】:

          将键作为集合元素分配为集合元素不能重复

          set1= {ele for ele in  file.read().split()}
          
          print(set1)
          

          【讨论】:

            【解决方案6】:

            你可以这样做:

            dict_ = {}
            with open("test.txt") as f:
                key = [line.split() for line in f]
            key = key[0]
            print(key)
            dict_ = dict((k,'any') for k in key)
            print(dict_)
            

            这给了你:

            ['HI', 'This', 'IS', 'A', 'TEST']
            {'HI': 'any', 'This': 'any', 'IS': 'any', 'A': 'any', 'TEST': 'any'}
            

            当文本文件包含时

            HI This IS A TEST
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-10-08
              • 1970-01-01
              相关资源
              最近更新 更多