-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkindlenotestomd.py
51 lines (40 loc) · 1.52 KB
/
kindlenotestomd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# A utility to convert saved notes from Kindle books (HTML) to markdown.
# Note headings (page number references) are contained in the 'noteHeading' class.
# The notes are contained in the 'noteText' class. This is what we want.
# Use the BeautifulSoup library to parse the html
from bs4 import BeautifulSoup
# Use pathlib to verify if the input file exists
import pathlib
notes = [] # A list to hold each note
# Get an input file to parse, and make sure it exists
while True:
input_file = input("Please enter a file name: ")
path = pathlib.Path(input_file)
# Make sure the input file exists
if path.is_file():
break
else:
print("Sorry, that file doesn't exist.")
continue
# Open an html file to parse
with open(input_file) as htmlnotes:
# # parse the file
soup = BeautifulSoup(htmlnotes, 'html.parser')
# # grab (only) the note text
for note in soup.find_all("div", class_="noteText"):
notes.append(note.get_text())
print("HTML file successfully converted to markdown.")
# Specify an output file name.
while True:
output_file = input("Please enter a file name to save the results: ")
path = pathlib.Path(output_file)
# Make sure the output file doesn't already exist
if path.is_file():
print("Sorry, that file already exists.")
continue
else:
break
# Save the parsed text to a file as a markdown list.
with open(output_file, 'a', newline='') as markdown:
for note in notes:
markdown.write("\n* " + note.strip() + '\n')