#include <bits/stdc++.h>
using namespace std;
vector<string> nhap_xau() {
  vector<string> res;
  string xau;
  getline(cin, xau);
  for (long long i = 0; i < xau.size(); i++)
    if (xau[i] == '?' || xau[i] == ',' || xau[i] == ')' || xau[i] == '(') {
      xau[i] = ' ';
    }
  istringstream ss(xau, istringstream ::in);
  string con;
  while (ss >> con) {
    res.push_back(con);
  }
  return res;
}
map<string, string> mp;
bool equal(vector<string> a, vector<string> b) {
  if (a.size() != b.size()) return 0;
  if (a[0] != b[0]) return 0;
  for (long long i = 0; i < a.size(); i++) {
    if (i == 0) continue;
    if (a[i] != "T" && mp[b[i]] != a[i]) {
      return 0;
    }
  }
  return 1;
}
vector<string> form[1005];
int main() {
  int n, m, k;
  string blank;
  cin >> n;
  getline(cin, blank);
  for (long long i = 1; i <= n; i++) {
    vector<string> u;
    u = nhap_xau();
    for (int j = 1; j < u.size(); j++) {
      form[i].push_back(u[j]);
    }
  }
  cin >> m;
  getline(cin, blank);
  for (long long i = 1; i <= m; i++) {
    vector<string> u;
    u = nhap_xau();
    mp[u[1]] = u[0];
  }
  cin >> k;
  getline(cin, blank);
  for (long long i = 1; i <= k; i++) {
    int ans = 0;
    vector<string> u;
    u = nhap_xau();
    for (long long khuon = 1; khuon <= n; khuon++) {
      if (equal(form[khuon], u)) ans++;
    }
    cout << ans << endl;
  }
}
