Skip to content

Instantly share code, notes, and snippets.

@ElnuDev
Created April 2, 2021 16:32
Show Gist options
  • Save ElnuDev/26c128e0dcdd5766d04c989a56e58e56 to your computer and use it in GitHub Desktop.
Save ElnuDev/26c128e0dcdd5766d04c989a56e58e56 to your computer and use it in GitHub Desktop.
Replace straight double quotation marks ("") and apostrophes (') with their curly equivelents, “” and ’.
file_path = input("File path: ")
f = open(file_path, 'r+')
original_text = f.read()
text = original_text
# Replace quotations
# https://stackoverflow.com/a/58567848
quote_count = text.count('"')
if quote_count % 2 == 1:
print("Invalid input. Number of quotation marks must be even. Exiting.")
exit()
for i in range(int(quote_count / 2 + 1)) :
text = text.replace('"', '“', 1)
text = text.replace('"', '”', 1)
print(f"Replaced {quote_count} quotes from text.")
# Replace apostrophes
apostrophe_count = text.count("'")
text = text.replace("'", "’")
print(f"Replaced {apostrophe_count} apostrophes from text.")
# Overwrite source file
# https://stackoverflow.com/a/2424410
f.seek(0)
f.write(text)
f.truncate()
f.close()
print(f"Overwrote {file_path} with fixed file.")
# Back up original file contents
f_backup_path = f"{file_path}.backup"
f_backup = open(f_backup_path, 'w')
f_backup.write(original_text)
f_backup.close()
print(f"Saved original {file_path} contents to {f_backup_path}.")
print("Done.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment