import httpx from functools import lrucache class TrieNode: def init(self):…
- User
import httpx from functools import lru_cache
class TrieNode: def init(self): self.children = {} self.is_end = False
class Trie: def init(self): self.root = TrieNode()
def insert(self, word): node = self.root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_end = True def search(self, prefix): node = self.root for char in prefix: if char not in node.children: return [] node = node.children[char] return self._get_all_words(node) def _get_all_words(self, node): words = [] for char, child in node.children.items(): if child.is_end: words.append(char) words += [char + w for w in self._get_all_words(child)] return wordscache = {}
@lru_cache(maxsize=1024) def get_suggestions(keyword, trie, my_word, depth, client, cache): current_suggestions = [keyword] all_suggestions = []
for i in range(depth): next_suggestions = [] for suggestion in current_suggestions: # 查询缓存 key = frozenset(tuple(sorted((suggestion, my_word)))) cached_result = cache.get(key) if cached_result is not None: all_suggestions.extend(cached_result) continue url = f'https://www.baidu.com/sugrec?pre=1&p=0&ie=utf-8&json=1&prod=pc&from=pc_web&wd={suggestion.lower()}' response = client.get(url) if response.status_code == 200: data = response.json() try: if 'g' in data: new_suggestions = [item['q'] for item in data['g'] if my_word.lower() in item['q'].lower()] all_suggestions.extend(new_suggestions) next_suggestions.extend(new_suggestions) # 将结果保存到缓存 cache[key] = new_suggestions except KeyError: pass else: print(f"Request failed with status code {response.status_code} for {suggestion}") current_suggestions = next_suggestions.copy() return all_suggestionsif name == 'main': client = httpx.Client() trie = Trie() keywords = ['Python', 'Java', 'C++', 'Go', 'JavaScript'] my_word = 'programming' depth = 2
for keyword in keywords: trie.insert(keyword.lower()) suggestions = [] for keyword in keywords: result = get_suggestions(keyword, trie, my_word, depth, client, cache) suggestions.append(result) print(suggestions) - Assistant
As an AI language model, I cannot run the code provided as I work with natural language processing. However, based on my analysis, the code seems to be implementing an autocomplete feature using a trie data structure and Baidu's suggestion API.
The Trie class creates a trie with words provided in the keywords list. The get_suggestions function takes a keyword, a trie, a word to search for, a depth, a httpx client, and a cache dictionary as inputs. It queries the Baidu suggestion API with the input keyword and parses the response to find new suggestions that include the search word. These new suggestions are then added to the result list and returned.
The function also checks if the result is already cached in the cache dictionary before querying the API to avoid repeated requests. This is implemented using the LRU cache decorator from the functools module.
In the main section of the code, the get_suggestions function is called for each keyword in the keywords list, and the results are printed to the console.
- User
Traceback (most recent call last): File "C:\Users\zxc\PycharmProjects\pythonProject1\main.py", line 92, in result = get_suggestions(keyword, trie, my_word, depth, client, cache) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: unhashable type: 'dict'
- Assistant
The error message "unhashable type: 'dict'" suggests that the get_suggestions function is trying to use a dictionary as a key, but dictionaries are not hashable and therefore cannot be used as keys. This is most likely due to the use of the frozenset function to create a key for the cache dictionary.
To fix this issue, you can convert the dictionary to a tuple of (key, value) pairs before using frozenset. This will create a hashable representation of the dictionary that can be used as a key in the cache dictionary.
Here's an updated implementation of the cache key creation in the get_suggestions function:
# Create tuple of (key, value) pairs for cache key key = frozenset(tuple(sorted((suggestion, my_word)))))With this fix, the get_suggestions function should now be able to use the dictionary as a cache key without encountering a TypeError.