Package: zensols.ngramdb
Create an SQLite database from the Google ngrams database.Creates an SQLite database of the one millionn-gramdatasets from Google.
This code downloads then-gram data setscorpus and then creates anSQLitedatabase file with the contents.  It also provides a simple API forn-gramlook ups.Table of ContentsInstallationData SizeUsageCommand LineProgrammatic InterfaceData Analysis with PandasObtainingChangelogLicenseInstallationTo make life easier, installGNU Make.  If you do not, you'll need to
follow the steps given in themakefile.Download the 1 millionn-gram data sets:make download.  This should
take a few minutes with a good Internet connection.Un-compress the load files:make uncompress.Create and load theSQLitedatabase from the downloaded corpus:make load.  Depending on the processor speed, this should take about an hour and
creates a file indata/eng-1gram.dbthat takes 18G on disk.Install from the command line either from source (make install) or frompip.If you want to use the program on the command line (as opposed to an API),
create a the following file in~/.ngramdbrcwith the contents:[default][ngram_db]data_dir=${HOME}/path/to/eng-1gram.dbData SizeAs mentioned, theSQLitedatabase file take 18G on disk.  This is because it
keeps occurrences over several decades.  In many cases, older n-grams are not
needed and queries can take a while given the size of the data.  The data can
be minimized with the following SQL in anySQLiteinterface (i.e. MacOS hassqlite3on the command line):deletefromngramwhereyr<1990;In this example, all n-grams recorded from publications before the year 1990
are expunged.UsageThis project can be used either from the command line or as an API.Command LineTo use from the command line:%ngramdbquery-gthe-y20056313626900.56880%This gives the number of unigrams (assuming unigrams were built) found since
2005 and the percentage of that unigram to all words in the corpus.Programmatic InterfaceAs in theinstallationsection, create the~/.ngramdbrcconfiguration file.  Also note that the API is configured to easily work with
other Python projects that use thezensols.actioncliconfiguration API.fromzensols.ngramdbimportAppConfig,Queryconf=AppConfig.instance().app_configquery=Query(conf)stash=query.stashn_occurs=stash['The']print(f'{n_occurs}{100*n_occurs/len(stash):.5f}%')=>6313626900.56880%Data Analysis with PandasThestash accessis nice for specific use cases
where a subset of the corpus counts are necessary.  However, the intention of
creating a selectable data format was to allow for data analysis as well.
Here's an example of howPandascan be used directly against the createdSQLitefile learn about the corpus:fromzensols.actioncli.timeimporttimeimportpandasaspdimportsqlite3ass# "connect" to the SQLite database filedb='/path/to/data/directory/eng-1gram.db'conn=s.connect(db)# create a dataframe with all entries on or after 1990sql='select grams, match_count as cnt from ngram where yr >= 1990'withtime('{rc}rows read'):df=pd.read_sql_query(sql,conn)rc=len(df)#=> 28150989 rows read finished in 60.8s# create a data frame with a ngram text and number of match counts per rowwithtime('groupby of{rc}rows'):dfg=df.groupby(['grams'],as_index=False).agg({'cnt':'sum'})rc=len(df)#=> group of 28150989 rows finished in 7.6s# get the number of counts on 'the'dfg[dfg['grams']=='the']#=>         grams        cnt#=> 2819462   the  621594750# all token occurrencesall_cnt=df['cnt'].sum()all_cnt#=> 13269089201# calculate at the poulation of a few wordsforwordin'the The . cat dog phone iPhone'.split():occ=dfg[dfg['grams']==word].cnt.item()pop=occ/all_cntprint(f'word\'{word}\'found{occ}times, which is{pop*100:.5f}% of the corpus')#=> word 'the' found 621594750 times, which is 4.68453% of the corpus#=> word 'The' found 77576794 times, which is 0.58464% of the corpus#=> word '.' found 641792317 times, which is 4.83675% of the corpus#=> word 'cat' found 247075 times, which is 0.00186% of the corpus#=> word 'dog' found 453789 times, which is 0.00342% of the corpus#=> word 'phone' found 522190 times, which is 0.00394% of the corpus#=> word 'iPhone' found 178 times, which is 0.00000% of the corpuswithtime('pickled data frame'):df.to_pickle('df.dat')#=> pickled data frame finished in 8.0swithtime('write to csv'):df.to_csv('df.csv')#=> write to csv finished in 44.3swithtime('read data from'):df=pd.read_pickle('df.dat')#=> read data from finished in 2.4sObtainingThe easist way to install the command line program is via thepipinstaller:pip3installzensols.ngramdbBinaries are also available onpypi.ChangelogAn extensive changelog is availablehere.LicenseCopyright (c) 2019 Paul LandesPermission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.