Bash
Usando as matrizes associativas do Bash :
#!/bin/bash
set -eu
declare -A patterns
while IFS= read -r p; do
patterns["$p"]=0
done < "$1"
while IFS='*' read -ra l; do
for r in "${l[@]}"; do
if [ -n "$r" ] && [ -v patterns["$r"] ]; then
patterns[$r]=$((${patterns["$r"]} + 1))
fi
done
done < "$2"
for p in "${!patterns[@]}"; do
printf '%s\t%u\n' "$p" "${patterns["$p"]}"
done
Uso:
bash count-patterns.sh pattern-list.txt word-list.txt
Python 3
Usando uma classe de dicionário personalizada e processamento de dados de estilo funcional:
#!/usr/bin/env python3
import sys, itertools, collections
class MyCounter(collections.UserDict):
def __init__(self, _dict):
self.data = _dict
def update(self, iterable):
for key in iterable:
self.data[key] += 1
with open(sys.argv[1]) as pattern_file:
patterns = MyCounter({ s.rstrip('\n'): 0 for s in pattern_file })
with open(sys.argv[2]) as wordlist_file:
patterns.update(filter(patterns.__contains__,
itertools.chain.from_iterable(map(
lambda s: s.rstrip('\n').split('**'), wordlist_file))))
for p in patterns.items():
print(*p, sep='\t')
Uso:
python3 count-patterns.py pattern-list.txt word-list.txt
C ++
#include <cstddef>
#include <utility>
#include <unordered_map>
#include <iostream>
#include <fstream>
namespace std
{
template <class Ch, class Tr, class K, class V, class H, class Eq>
basic_ostream<Ch,Tr> &operator<<( basic_ostream<Ch,Tr> &os,
const std::unordered_map<K,V,H,Eq> &m )
{
for (const typename std::unordered_map<K,V,H,Eq>::value_type &i: m)
os << i.first << '\t' << i.second << '\n';
return os.flush();
}
}
template <class Key, class Hash = std::hash<Key>, class Equal = std::equal_to<Key>>
class counter :
public std::unordered_map<Key, std::size_t, Hash, Equal>
{
private:
typedef std::unordered_map<Key, std::size_t, Hash, Equal> _base;
public:
void update_existing( const Key &k, std::size_t count = 1 )
{
const typename _base::iterator match = this->find(k);
if (match != this->end())
match->second += count;
}
};
int main( int argc, char *argv[] )
{
if (argc != 3)
{
std::cerr << "Usage: " << argv[0] << " <PATTERN-FILE> <WORDLIST-FILE>" << std::endl;
return 2;
}
counter<std::string> patterns;
std::string buf;
{
std::ifstream pattern_file(argv[1]);
while (pattern_file.good() && !std::getline(pattern_file, buf).fail())
patterns.emplace(std::move(buf), 0);
}
if (!patterns.empty())
{
std::ifstream wordlist_file(argv[2]);
while (wordlist_file.good() && !std::getline(wordlist_file, buf).fail())
{
static const char delim[] = {'*', '*'};
std::size_t offset = 0, p = 0;
while ((p = buf.find(delim, offset, sizeof(delim))) != std::string::npos)
{
patterns.update_existing(buf.substr(offset, p - offset));
offset = p + sizeof(delim);
}
patterns.update_existing(buf.erase(0, offset));
}
}
std::cout << patterns;
}
Compile com:
c++ -std=c++11 -o count-patterns count-patterns.cpp
Uso:
./count-patterns pattern-list.txt word-list.txt