我有一个字典(inverted_index),它将整数键映射到所有列表值:
key value
101332 1011772 10841334 21363790
101334 1142902
101347 764543
我尝试使用命名管道,以便用户可以输入密钥,然后结果将是值列表。但是,我没有得到任何结果。
以下是我尝试过的代码:
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)
以下是我得到的结果:
Terminal 1: $ python dictpipes.py
Opening FIFO...
Terminal 2: $ echo 101332 | bc > dictpipe
Terminal 1: $ python dictpipes.py
Opening FIFO...
FIFO opened
[[], [], [], [], [], [], []]
Writer closed
正如您所看到的,我获得了一个空列表列表..结果应该是: [1011772,10841335,21363790]
修改 用于创建字典的代码..
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)
答案 0 :(得分:0)
您将输入为字符串,而for x in inp
中的getDocuments
将遍历字符串的字符。它找不到对应于" 1"," 0"," 1"," 3"," 3& #34;,或" 2"所以返回一个空列表列表。相反(假设键在字典中存储为整数),请尝试:
def getDocuments(inp):
return inverted_index[int(inp)]
或者,如果您希望用户能够输入多个以空格分隔的键,则可以通过拆分输入来完成此操作:
def getDocuments(inp)
return [inverted_index[int(x)] for x in inp.split()]
修改强>
由于您的字典是从文本文件构建的,因此键必须是字符串。因此,您只需要在进行查找之前从用户的输入中删除任何空格(包括换行符#34; \ n")。
return inverted_index[inp.strip()]
或者使用整数而不是字符串构建字典,并使用上面的第一个getDocuments
函数。
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)