Python 如何制作一本英文单词为关键字、希腊文单词为值的词典(utf-8),i';当我试图获取值时,我得到一个keyrerror
我试图举例说明一本翻译词典:Python 如何制作一本英文单词为关键字、希腊文单词为值的词典(utf-8),i';当我试图获取值时,我得到一个keyrerror,python,dictionary,utf-8,Python,Dictionary,Utf 8,我试图举例说明一本翻译词典: 当一个单词用英语给出时,我用希腊语(utf-8)返回其含义 注意:该文件包含此类字符串:“Hello,Γεια\n”和“Car,Αμαξ\n” 错误:print(字典[word])抛出一个键错误 这是Python2.7 事先非常感谢问题的实现需要两个循环。外环穿过行,内环穿过当前行的字符,例如: for line in lines: for i in range(0, len(line)): # Then using line[i] i
- 当一个单词用英语给出时,我用希腊语(utf-8)返回其含义
事先非常感谢问题的实现需要两个循环。外环穿过行,内环穿过当前行的字符,例如:
for line in lines:
for i in range(0, len(line)):
# Then using line[i] instead of lines[i]
另外,read()
获取全部内容,readlines()
是正确的函数
下面的实现使用split(',')
来分隔一行中的单词。
此外,可以通过简单的字典[key]=value
更新字典。
导入编解码器
with codecs.open("dict.txt", 'r', encoding='utf8') as f:
lines = f.readlines()
word=raw_input("Word To Find\n")
dictionary={}
for line in lines:
if ',' in line:
key, value = line.split(',')
dictionary[key.strip()] = value.strip()
else:
print('Cannot parse line: ' + line)
if word in dictionary:
print(dictionary[word])
else:
print('Error: Translation not found.')
前面的实现假定该值不带逗号。
以下版本允许在值中使用逗号:
for line in lines:
comma_index = line.index(',')
if comma_index >= 0:
key = line[0:comma_index]
value = line[comma_index + 1:]
dictionary[key.strip()] = value.strip()
else:
print('Cannot parse line: ' + line)
您的拆分算法有点问题,而且由于python中内置了对执行相同任务的支持,为什么要重新发明轮子
import io
with io.open("test.txt",'r',encoding='utf8') as f:
list_of_lines= f.read().splitlines() #contains all the lines of the file in a list
dictionary={}
for line in list_of_lines:
eng, greek = line.split(',') # split(',') will split the string by ',' and make a list out of it
dictionary[eng] = greek
print(dictionary['Hello'])
调试的第一步:
打印(dictionary.keys())
。调试完成。修复代码的步骤1:dic_file=open('dict.txt');dictionary={e:g.strip()表示e,g in(line.split(',')表示dic_文件中的line)}
。如果我打印名为“line”的dictionaryOP,我会得到11次相同的内容,但实际上它不是一个行列表;它是一个包含文件全部内容的字符串。所以不,这不是问题所在。为什么不遍历行本身:对于c,在行:
?@YevhenKuzmovych如果不需要,我根本不会遍历字符。更新后的答案使用了一个简单的split(',')
。出于某种原因,我收到了一个类型错误:“encoding”是此函数行的无效关键字参数:将open(“dict.txt”,“r',encoding='utf8')作为f:这是因为您使用的是python2,这是python3的解决方案。让我稍后发布修复程序。@Phill,答案已更新,将在python2中使用。
import io
with io.open("test.txt",'r',encoding='utf8') as f:
list_of_lines= f.read().splitlines() #contains all the lines of the file in a list
dictionary={}
for line in list_of_lines:
eng, greek = line.split(',') # split(',') will split the string by ',' and make a list out of it
dictionary[eng] = greek
print(dictionary['Hello'])