Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将单词保存为键的功能_Python_Python 3.x_Dictionary_Pycharm_Key - Fatal编程技术网

Python 将单词保存为键的功能

Python 将单词保存为键的功能,python,python-3.x,dictionary,pycharm,key,Python,Python 3.x,Dictionary,Pycharm,Key,我正在尝试编写一个函数,读取.txt文件中包含的单词,并将它们作为键写入字典。该值可以是任意值。程序应该允许我使用in运算符检查字符串是否在字典中 我试过这样的方法: words = open('words.txt') def k(): for word in words: key = word[0] print(k) dict_ = {} with open("test.txt") as f: key = [line.split() for line in

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

我试过这样的方法:

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

print(k)
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_)

我不知道怎么做。有人能帮我吗?

这个词实际上是你说的。没有必要将索引设置为0

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

我认为您需要读取一个文件并遍历其行,然后保存每行的第一个字。由于某些原因,
with open
语法比直接打开文件要好。请尝试以下代码:

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

您可以这样做:

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

print(k)
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
file=open(“C:/Users/sghungurde/Documents/love.txt”)


不能重复将键指定为集合元素作为集合元素

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

print(set1)

这些键的值应该是什么?在
python
中没有
value
s的
dictionary
称为
set
。您可以使用以下工具轻松创建它:
words\u set=set(words)
字典不仅仅是键,它们包含成对的键和值,您可以编辑您的问题以给出预期输出的示例吗?值也可以是任意值,您提供的代码显示您可能不知道如何调用函数,如何从函数返回值,如何读取文件,字典到底是什么。我强烈建议回到python的基础知识上来