#include <bits/stdc++.h>
using namespace std;
vector<string> parse(string line) {
  for (register int i = (0); i < (int)(((int)(line).size())); ++i)
    if (line[i] == ',' || line[i] == '(' || line[i] == ')') line[i] = ' ';
  istringstream sin(line);
  vector<string> V;
  string s;
  while (sin >> s) V.push_back(s);
  return V;
}
vector<pair<string, vector<string> > > func;
map<string, string> types;
int main() {
  ios::sync_with_stdio(false);
  int n;
  cin >> n;
  while (cin.get() != '\n')
    ;
  while (n--) {
    string line;
    getline(cin, line);
    vector<string> V = parse(line);
    string name = V[1];
    vector<string> param;
    for (register int i = (2); i < (int)(((int)(V).size())); ++i)
      param.push_back(V[i]);
    func.push_back(make_pair(name, param));
  }
  cin >> n;
  while (cin.get() != '\n')
    ;
  while (n--) {
    string line;
    getline(cin, line);
    vector<string> V = parse(line);
    types[V[1]] = V[0];
  }
  cin >> n;
  while (cin.get() != '\n')
    ;
  while (n--) {
    string line;
    getline(cin, line);
    vector<string> V = parse(line);
    int tot = 0;
    for (__typeof((func).begin()) it = (func).begin(); it != (func).end(); ++it)
      if (it->first == V[0] &&
          ((int)(V).size()) - 1 == ((int)(it->second).size())) {
        bool ok = true;
        for (register int i = (0); i < (int)(((int)(it->second).size())); ++i) {
          if (it->second[i] == "T") continue;
          if (it->second[i] != types[V[i + 1]]) {
            ok = false;
            break;
          }
        }
        if (ok) tot++;
      }
    cout << tot << endl;
  }
  return 0;
}
