簡體   English   中英

Python從給定的txt文件創建字典

[英]Python create dictionary from a given txt file

任務:給定一個txt文件,一行中含有形容詞\\t同義詞、同義詞、同義詞等,給出幾行。 我需要創建一個字典,其中形容詞將是一個鍵和同義詞 - 一個值。 我的代碼:

#necessary for command-line 
import sys 

#open file for reading
filename = sys.argv[1]
infile = open(filename, "r")

#a
#create a dictionary, where an adjective in a line is a key
#and synonyms are the value
dict = {}

#for each line in filename
for line in filename:
    #key is everything before tab, value - after the tab
    key, value = line.strip().split("\t")
    dict[key.strip()] = value.strip()

#close the file
filename.close()

終端顯示錯誤:

    key, value = line.strip().split("\t")
ValueError: not enough values to unpack (expected 2, got 1)

有人可以幫忙修復嗎?

filename只是一個字符串而不是你的文件,file 是infile所以你應該在 infile 中for 行:最后它是infile.close()但我認為這可能仍然不能解決你的問題,你會得到列表作為結果來自line.strip().split("\\t") ,雖然有兩個元素,但編譯器不知道一行中可能有多少個選項卡,所以你不能像這樣解壓它。

問題在於您的文件處理。 您使用filename作為文件對象而不是infile ,如果出現錯誤,文件將不會被關閉。 重寫你的代碼:

#necessary for command-line 
import sys 

#open file for reading
filename = sys.argv[1]

#a
#create a dictionary, where an adjective in a line is a key
#and synonyms are the value
dict = {}

with open(filename, "r") as infile:
    #for each line in infile
    for line in infile:
        #key is everything before tab, value - after the tab
        key, value = line.strip().split("\t")
        dict[key.strip()] = value.strip()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM