0

Task: given a txt file with adjective \t synonym, synonym, synonym, etc. in a line, several lines are given. I need to create a dictionary, where adjective will be a key and synonyms - a value. My code:

#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()

Terminal shows the error:

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

Could someone help to fix?

msanford
  • 11,803
  • 11
  • 66
  • 93
Luiza
  • 1
  • 1
  • 4
    can you post a sample of how the txt file looks like? – Minions Nov 06 '20 at 22:57
  • Does this answer your question? [splitting a string based on tab in the file](https://stackoverflow.com/questions/17038426/splitting-a-string-based-on-tab-in-the-file) – msanford Nov 06 '20 at 23:06
  • 1
    Simple debugging will give you a clue: in your for loop, try `print(line.strip().split("\t"))` and see what you get. It goes along with your "not enough values to unpack" error. Also, I think you mean `for line in infile` not `filename`... – msanford Nov 06 '20 at 23:07
  • 1
    You're simply having a `line` that doesn't contains a `\t` so the `split` cannot give you 2 members. As suggested by @mansford, if your code is verbatim then you're iterating over the chars of `filename` instead of the lines of `infile`, which would explain that `split` doesn't have much to split in multiple parts. – zigarn Nov 06 '20 at 23:14

2 Answers2

0

filename is just a string not your file, file is infile so you should have for line in infile: and at the end it's infile.close() But I think that will still probably not solve your problem, you will get the list as result from the line.strip().split("\t"), with two elements though, but the compiler doesn't know how many tabs may be in a line, so you can't unpack it like this.

Bran
  • 71
  • 5
0

The problem is with your file handling. You use filename as the file object instead of infile and if an error is raised, the file won't be closed. Rewrite of your code:

#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()
Roy Cohen
  • 1,540
  • 1
  • 5
  • 22