I have one dictionary (inverted_index) that maps integer keys to list values all follows:
key value
101332 1011772 10841334 21363790
101334 1142902
101347 764543
I'm trying to use named pipes so that the user can input a key and then the result will be the list of values. However, I'm not getting any result.
The following is the code I tried:
import os
import errno
def getDocuments(inp):
return [inverted_index[x] for x in inp]
FIFO = 'dictpipe'
try:
os.mkfifo(FIFO)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
print("Opening FIFO...")
with open(FIFO) as fifo:
print("FIFO opened")
data = set()
while True:
data = fifo.read()
if len(data) == 0:
print("Writer closed")
break
dd = getDocuments(data)
print(dd)
The following is the result I'm getting:
Terminal 1: $ python dictpipes.py
Opening FIFO...
Terminal 2: $ echo 101332 | bc > dictpipe
Terminal 1: $ python dictpipes.py
Opening FIFO...
FIFO opened
[[], [], [], [], [], [], []]
Writer closed
As you can see I'm getting a list of empty lists.. the result should be: [1011772, 10841335, 21363790]
Edit: The code used to create the dictionary..
from collections import defaultdict
inverted_index = defaultdict(list) #inverted index dictionary
forward_index = defaultdict(list) #forward index dictionary
with open('term_dict.txt') as file:
for line in file:
items = line.split()
term, doc = items[0], items[1:]
for doc in items[1:]:
inverted_index[term].append(doc)
forward_index[doc].append(term)
You are getting input as a string and for x in inp
in getDocuments
iterates through the characters of the string. It finds no values in the dicationary corresponding to "1", "0", "1", "3", "3", or "2" so returns a list of empty lists. Instead (assuming keys are stored as integers in your dictionary), try:
def getDocuments(inp):
return inverted_index[int(inp)]
Or, if you want the user to be able to enter more than one key, separated by spaces, you can do this by splitting the input:
def getDocuments(inp)
return [inverted_index[int(x)] for x in inp.split()]
EDIT
As your dictionary is built from a text file, the keys must be strings. So you just need to strip any whitespace (including the newline character "\\n") from the user's input before doing the look-up.
return inverted_index[inp.strip()]
Alternatively build your dictionary with integers instead of strings, and use the first getDocuments
function above.
with open('term_dict.txt') as file:
for line in file:
items = line.split()
term = int(items[0])
for doc in items[1:]:
doc_int = int(doc)
inverted_index[term].append(doc_int)
forward_index[doc_int].append(term)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.