This notebook uses word frequency to explore the OCRd texts harvested from Trove's digitised journals. More documentation coming...
import os
import re
# import tarfile
import zipfile
from io import BytesIO
from pathlib import Path
import altair as alt
import ipywidgets as widgets
import numpy as np
import pandas as pd
import requests
from IPython.display import display
from sklearn.feature_extraction.text import CountVectorizer
Create a dropdown widget to select a digitised journal. The cells below will use this widget to get the value of the currently selected journal.
# Load details of digitised journals from CSV
df_journals = pd.read_csv("digital-journals-with-text-20220831.csv").sort_values(
by="title"
)
journal_list = [
(f"{j['title']} ({j['issues_with_text']} issues)", j["directory"])
for j in df_journals[["title", "directory", "issues_with_text"]].to_dict("records")
]
journals = widgets.Dropdown(options=journal_list, disabled=False)
display(journals)
def get_docs_path(journal):
path = os.path.join("downloads", journal, "texts")
docs_path = [p for p in sorted(Path(path).glob("*.txt"))]
return docs_path
def download_journal(journal):
path = os.path.join("downloads", journal)
os.makedirs(path, exist_ok=True)
params = {"path": f"/{journal}/texts"}
response = requests.get(
"https://cloudstor.aarnet.edu.au/plus/s/QOmnqpGQCNCSC2h/download", params=params
)
zipped = zipfile.ZipFile(BytesIO(response.content))
zipped.extractall(path)
print(f"{len(get_docs_path(journal))} issues downloaded")
download_journal(journals.value)
def get_docs(journal):
docs_path = get_docs_path(journal)
for p in docs_path:
yield p.read_text(encoding="utf-8").strip()
def get_file_names(journal):
return [p.stem for p in get_docs_path(journal)]
# Remove numbers
# preprocessor = lambda x: re.sub(r'\b(\w*\d\w*)\b', 'NUM', x.lower())
vectorizer = CountVectorizer(
stop_words="english",
ngram_range=(1, 1),
token_pattern="[a-z]{3,}",
lowercase=True,
max_features=100000,
)
X_freq = np.asarray(vectorizer.fit_transform(get_docs(journals.value)).todense())
df_freq = pd.DataFrame(
X_freq,
columns=vectorizer.get_feature_names_out(),
index=get_file_names(journals.value),
)
# Save to CSV
df_freq.to_csv(f"{journals.value}-word-frequencies.csv")
np.save(f"{journals.value}-word-frequencies.npy", X_freq)
df_freq.shape
totals = df_freq.sum().to_frame().reset_index()
totals.columns = ["word", "count"]
totals.loc[totals["count"] > 180].shape
totals
Change the number as you wish.
df_freq.sum().nlargest(20)
word = "knoll"
# If the word's not in the index you'll get a KeyError -- don't worry about it, just try another word!!
df_freq[word].sum()
Find the issue that this word occurs in most frequently.
df_freq[word].idxmax()
Get the most frequent words for each issue of the journal. Set num_words
to the number of words you want to show.
# The number of words you want to show
num_words = 20
top_words = pd.DataFrame(
{
n: df_freq.T[col].nlargest(num_words).index.tolist()
for n, col in enumerate(df_freq.T)
}
).T
top_words.index = get_file_names(journals.value)
top_words.head()
Get the top words for a specific issue.
top_words.loc[top_words.index.str.contains("nla.obj-9139951")]
def extract_year(name):
"""
Try to extract the year from the filename.
"""
try:
years = re.findall(r"-((?:18|19|20)\d{2})-", name)
year = int(years[-1])
except IndexError:
year = 0
print(f"YEAR NOT FOUND: {name}")
return year
df_freq["year"] = df_freq.apply(lambda x: extract_year(x.name), axis=1)
# Top words per year
year_groups = df_freq.groupby(by="year")
year_group_totals = year_groups.sum()
df_years = pd.DataFrame(
{
n: year_group_totals.T[col].nlargest(10).index.tolist()
for n, col in enumerate(year_group_totals.T)
}
).T
df_years.index = [name for name, _ in year_groups]
df_years.head()
year_group_totals.to_csv("words_by_year.csv")
year_group_totals["total_words"] = year_group_totals.sum(axis=1)
def words_by_year(df, words):
df_words = pd.DataFrame()
for word in words:
try:
df_word = (
df.groupby(by="year")
.sum()[word]
.to_frame()
.reset_index()
.rename({word: "count"}, axis=1)
)
except KeyError:
print(f"'{word}' not found")
else:
df_word["word"] = word
df_words = df_words.append(df_word, ignore_index=True)
return df_words
Make a list of words that we want to compare.
words = ["nation", "chinese", "republic", "worker", "unions", "union", "labor"]
Get the data for those words.
df_words = words_by_year(df_freq, words)
Create a faceted line chart.
alt.Chart(df_words.loc[df_words["year"] > 0]).mark_line().encode(
x=alt.X("year:Q", axis=alt.Axis(format="c", title="Year")),
y="count:Q",
color="word:N",
facet="word:N",
).properties(width=700, height=100, columns=1)
Or perhaps you prefer bubblelines.
# Create a chart
alt.Chart(df_words.loc[df_words["year"] > 0]).mark_circle(
# Style the circles
opacity=0.8,
stroke="black",
strokeWidth=1,
).encode(
# Year on the X axis
x=alt.X("year:O", axis=alt.Axis(format="c", title="Year", labelAngle=0)),
# Object type on the Y axis
y=alt.Y("word:N", title="Word"),
# Size of the circles represents the number of objects
size=alt.Size(
"count:Q",
scale=alt.Scale(range=[0, 1000]),
legend=alt.Legend(title="Frequency"),
),
# Color the circles by object type
color=alt.Color("word:N", legend=None),
# More details on hover
tooltip=[
alt.Tooltip("word:N", title="Word"),
alt.Tooltip("year:O", title="Year"),
alt.Tooltip("count:Q", title="Frequency", format=","),
],
).properties(
width=700, height=300
)