#include <bits/stdc++.h>
using namespace std;
template <typename T0, typename T1>
std::ostream& operator<<(std::ostream& os, const map<T0, T1>& v) {
  for (typename map<T0, T1>::const_iterator p = v.begin(); p != v.end(); p++) {
    os << p->first << ": " << p->second << " ";
  }
  return os;
}
template <typename T0, typename T1>
std::ostream& operator<<(std::ostream& os, const pair<T0, T1>& v) {
  os << v.first << ": " << v.second << " ";
  return os;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const vector<vector<T> >& v) {
  for (int i = 0; i < (int)v.size(); i++) {
    os << v[i] << endl;
  }
  return os;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const vector<T>& v) {
  for (int i = 0; i < (int)v.size(); i++) {
    os << v[i] << " ";
  }
  return os;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const set<T>& v) {
  vector<T> tmp(v.B, v.E);
  os << tmp;
  return os;
}
int check(vector<string>& call, vector<vector<string> >& defs) {
  int ans = 0;
  for (long long i = 0, _n = (defs.size()); (i) < (int)_n; ++i) {
    if (defs[i].size() != call.size()) continue;
    int ok = 1;
    for (long long j = 0, _n = (defs[i].size()); (j) < (int)_n; ++j) {
      if (!(defs[i][j] == "T" || defs[i][j] == call[j])) ok = 0;
    }
    ans += ok;
  }
  return ans;
}
int main() {
  int N, M, K;
  while (cin >> N) {
    vector<vector<string> > defs;
    map<string, string> vars;
    string s;
    getline(cin, s);
    for (long long i = 0, _n = (N); (i) < (int)_n; ++i) {
      vector<string> def;
      getline(cin, s);
      for (long long i = 0, _n = (s.size()); (i) < (int)_n; ++i) {
        if (s[i] == '(' || s[i] == ')' || s[i] == ',') s[i] = ' ';
      }
      stringstream ss(s);
      ss >> s;
      ss >> s;
      def.push_back(s);
      while (ss >> s) {
        def.push_back(s);
      }
      defs.push_back(def);
    }
    cin >> M;
    for (long long i = 0, _n = (M); (i) < (int)_n; ++i) {
      string ty, name;
      cin >> ty >> name;
      vars[name] = ty;
    }
    cin >> K;
    getline(cin, s);
    for (long long i = 0, _n = (K); (i) < (int)_n; ++i) {
      getline(cin, s);
      for (long long i = 0, _n = (s.size()); (i) < (int)_n; ++i) {
        if (s[i] == '(' || s[i] == ')' || s[i] == ',') s[i] = ' ';
      }
      stringstream ss(s);
      vector<string> call;
      ss >> s;
      call.push_back(s);
      while (ss >> s) {
        call.push_back(vars[s]);
      }
      cout << check(call, defs) << endl;
    }
  }
  return 0;
}
