-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat: Improve chardict.py
to add n-gram counts
#9
Open
Ced-C
wants to merge
12
commits into
OneDeadKey:main
Choose a base branch
from
Ced-C:improve-chardict
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
cdc8b29
Feat: Improve `chardict.py` to add n-gram counts
f69cf2a
minor fixes
fabi1cazenave d88560e
Refactor: Following #9 advise, cleaned up the code to be simpler and …
6d3d91b
Merge branch 'main' into improve-chardict
fabi1cazenave d0593ed
Refactor: `merge.read_corpora` dropping dict of corpus for a list ins…
ac3e971
Refactor: adding `merge.mergable` to check if merge can be processed.
3832f64
Refactor : updating `merge.mix` to follow #9 guidelines (no empty lis…
6e59e64
Refactor: addressing #9 comment that it should be in another PR
c161070
Refactor: `merge.sort_by_frequency` good practice to **not** change v…
f7e27e1
Refactor: removing “name” field from corpus json files
52be518
Chore: typo fix in comments
be99fc2
Chore: Finish PR review and drop "name" field
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,78 +1,113 @@ | ||
#!/usr/bin/env python3 | ||
"""Turn corpus texts into dictionaries of symbols, bigrams and trigrams.""" | ||
"""Turn corpus texts into dictionaries of n-grams.""" | ||
|
||
import json | ||
from os import listdir, path | ||
from pathlib import Path | ||
from sys import argv | ||
|
||
IGNORED_CHARS = "1234567890 \t\r\n\ufeff" | ||
|
||
|
||
def parse_corpus(file_path): | ||
"""Count symbols, bigrams and trigrams in a text file.""" | ||
|
||
symbols = {} | ||
bigrams = {} | ||
trigrams = {} | ||
char_count = 0 | ||
prev_symbol = None | ||
prev_prev_symbol = None | ||
|
||
# get a dictionary of all symbols (letters, punctuation marks...) | ||
file = open(file_path, "r", encoding="utf-8") | ||
for char in file.read(): | ||
symbol = char.lower() | ||
if char not in IGNORED_CHARS: | ||
char_count += 1 | ||
if symbol not in symbols: | ||
symbols[symbol] = 0 | ||
symbols[symbol] += 1 | ||
if prev_symbol is not None: | ||
bigram = prev_symbol + symbol | ||
if bigram not in bigrams: | ||
bigrams[bigram] = 0 | ||
bigrams[bigram] += 1 | ||
if prev_prev_symbol is not None: | ||
trigram = prev_prev_symbol + bigram | ||
if trigram not in trigrams: | ||
trigrams[trigram] = 0 | ||
trigrams[trigram] += 1 | ||
prev_prev_symbol = prev_symbol | ||
prev_symbol = symbol | ||
else: | ||
prev_symbol = None | ||
file.close() | ||
NGRAM_MAX_LENGTH = 4 # trigrams | ||
IGNORED_CHARS = "1234567890 \t\r\n\ufeff↵" | ||
|
||
|
||
def parse_corpus(txt: str) -> dict: | ||
"""Count ngrams in a string. | ||
retuns a dict of ngrams | ||
ngrams[1]=symbols | ||
ngrams[2]=bigrames | ||
ngrams[3]=trigrams | ||
etc., up to NGRAM_MAX_LENGTH | ||
ngrams[2] is shaped as { "aa": count } | ||
""" | ||
|
||
ngrams = {} | ||
ngrams_count = {} # ngrams_count counts the total number of ngrams[i] in corpus. | ||
|
||
txt = txt.lower() # we want to be case **in**sensitive | ||
|
||
for ngram in range(1, NGRAM_MAX_LENGTH): | ||
ngrams[ngram] = {} | ||
ngrams_count[ngram] = 0 | ||
|
||
def get_ngram(txt: str, ngram_start: int, ngram_length: int) -> str: | ||
"""get a ngram of a given length at given position in txt | ||
returns empty string if ngram cannot be provided""" | ||
if txt[ngram_start] in IGNORED_CHARS: | ||
return "" | ||
if ngram_length <= 0: | ||
return "" | ||
if ngram_start + ngram_length >= len(txt): | ||
return "" | ||
|
||
ngram = txt[ngram_start : ngram_start + ngram_length] | ||
|
||
for n in ngram[1:]: # 1st char already tested | ||
if n in IGNORED_CHARS: | ||
return "" | ||
|
||
return ngram | ||
|
||
# get all n-grams | ||
for ngram_start in range(len(txt)): | ||
for ngram_length in range(NGRAM_MAX_LENGTH): | ||
_ngram = get_ngram(txt, ngram_start, ngram_length) | ||
|
||
if not _ngram: # _ngram is "" | ||
continue | ||
|
||
if _ngram not in ngrams[ngram_length]: | ||
ngrams[ngram_length][_ngram] = 0 | ||
|
||
ngrams[ngram_length][_ngram] += 1 | ||
ngrams_count[ngram_length] += 1 | ||
|
||
# sort the dictionary by symbol frequency (requires CPython 3.6+) | ||
def sort_by_frequency(table, precision=3): | ||
def sort_by_frequency(table: dict, char_count: int, precision: int = 3) -> dict: | ||
sorted_dict = {} | ||
for key, count in sorted(table.items(), key=lambda x: -x[1]): | ||
freq = round(100 * count / char_count, precision) | ||
if freq > 0: | ||
sorted_dict[key] = freq | ||
return sorted_dict | ||
|
||
results = {} | ||
results["corpus"] = file_path | ||
results["symbols"] = sort_by_frequency(symbols) | ||
results["bigrams"] = sort_by_frequency(bigrams, 4) | ||
results["trigrams"] = sort_by_frequency(trigrams) | ||
return results | ||
for ngram in range(1, NGRAM_MAX_LENGTH): | ||
ngrams[ngram] = sort_by_frequency(ngrams[ngram], ngrams_count[ngram], 4) | ||
|
||
return ngrams, ngrams_count | ||
|
||
|
||
def read_corpus(file: Path, encoding="utf-8") -> dict: | ||
"""read a .txt file and provide a dictionary of n-grams""" | ||
try: | ||
if not file.is_file: | ||
raise Exception("Error, this is not a file") | ||
with file.open("r", encoding=encoding) as f: | ||
corpus_txt = "↵".join(f.readlines()) | ||
|
||
except Exception as e: | ||
print(f"file does not exist or could not be read.\n {e}") | ||
|
||
ngrams_freq, ngrams_count = parse_corpus(corpus_txt) | ||
return { | ||
"freq": ngrams_freq, | ||
"count": ngrams_count, | ||
} | ||
|
||
|
||
if __name__ == "__main__": | ||
if len(argv) == 2: # convert one file | ||
data = parse_corpus(argv[1]) | ||
file = Path(argv[1]) | ||
data = read_corpus(file) | ||
output_file_path = file.parent / f"{file.stem}.json" | ||
with open(output_file_path, "w", encoding="utf-8") as outfile: | ||
json.dump(data, outfile, indent=4, ensure_ascii=False) | ||
print(json.dumps(data, indent=4, ensure_ascii=False)) | ||
|
||
else: # converts all *.txt files in the script directory | ||
bin_dir = path.dirname(__file__) | ||
destdir = path.join(bin_dir, "..", "txt") | ||
txtdir = path.join(bin_dir, "..", "txt") | ||
for filename in listdir(txtdir): | ||
if filename.endswith(".txt"): | ||
basename = filename[:-4] | ||
print(f"... {basename}") | ||
data = parse_corpus(path.join(txtdir, filename)) | ||
destfile = path.join(destdir, basename + ".json") | ||
with open(destfile, "w", encoding="utf-8") as outfile: | ||
txt_dir = Path(__file__).resolve().parent.parent / "txt" | ||
for file in sorted(txt_dir.glob("*.txt")): | ||
if file.is_file(): | ||
print(f"... {file.stem}") | ||
data = read_corpus(file) | ||
output_file_path = txt_dir / f"{file.stem}.json" | ||
with open(output_file_path, "w", encoding="utf-8") as outfile: | ||
json.dump(data, outfile, indent=4, ensure_ascii=False) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This works and the logic is simple (I like that), but I’m not a fan of how it’s implemented. If that’s okay with you:
main
branch (this PR is based on a previous version)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Eager to see what changes you are thinking about.
I was pretty sure this was simple enough to be accepted but maybe it’s performance-wise that you would like to improve things ?