Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5d7b225

Browse files
committed
Python timefriend
1 parent 76ae98d commit 5d7b225

File tree

2 files changed

+257
-0
lines changed

2 files changed

+257
-0
lines changed

‎timefriend/test.py‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import unittest
2+
import evernote.edam.userstore.constants as UserStoreConstants
3+
from app import EverNote
4+
5+
class TestEvernote(unittest.TestCase):
6+
# def setUp(self):
7+
auth_token = "S=s1:U<...>5369" # 换成自己的 token
8+
client = EverNote(auth_token)
9+
10+
tagGuid = "d62cafaa-dcc1-4f41-b727-8a5a1f950f95"
11+
noteName = "2020年03月13日"
12+
tagName= "时间账"
13+
notebookName = "时间的朋友"
14+
15+
def test_init(self):
16+
user_store = self.client.client.get_user_store()
17+
version_ok = user_store.checkVersion(
18+
"Evernote EDAMTest (Python)",
19+
UserStoreConstants.EDAM_VERSION_MAJOR,
20+
UserStoreConstants.EDAM_VERSION_MINOR
21+
)
22+
self.assertIs(version_ok, True, "版本有问题")
23+
24+
def test_getTagGuid(self):
25+
self.assertEqual(self.client.getTagGuid(self.tagName), self.tagGuid, "获取的 TagGuid 不对")
26+
27+
def test_getNotebookGuid(self):
28+
self.assertIsNotNone(self.client.getNotebookGuid(self.notebookName), "获取不到笔记本Guid")
29+
30+
def test_getNoteGuidByTagGuid(self):
31+
noteGuid = self.client.getNoteGuidByTagGuid(self.noteName, self.tagGuid)
32+
self.assertIsNotNone(noteGuid, "无法获取笔记")
33+
34+
def test_getNoteContent(self):
35+
noteGuid = self.client.getNoteGuidByTagGuid(self.noteName, self.tagGuid)
36+
content = self.client.getNoteContent(noteGuid)
37+
self.assertIsNot(content, "", "无法获取到笔记内容")
38+
39+
def test_formatLine(self):
40+
ftext = self.client.formatLine("测试文本 测试 这是测试 ")
41+
self.assertEqual(ftext, "<div>测试文本&nbsp; &nbsp; 测试 这是测试&nbsp; &nbsp; </div>", "行格式化失败")
42+
ftext2 = self.client.formatLine("")
43+
self.assertEqual(ftext2, "<div><br/></div>", "行无法格式化空行")
44+
45+
def test_createNote(self):
46+
content = "测试笔记 测试用\n换行"
47+
noteGuid = self.client.createNote("测试笔记",content)
48+
noteContent = self.client.getNoteText(noteGuid)
49+
self.assertEqual("测试笔记 测试用\n\n换行\n\n", noteContent, "创建笔记失败")
50+
def test_updateNote(self):
51+
tagGuid = self.client.getTagGuid("测试")
52+
noteGuid = self.client.getNoteGuidByTagGuid("测试笔记", tagGuid)
53+
self.client.updateNote(noteGuid, "添加的内容")
54+
noteContent = self.client.getNoteText(noteGuid)
55+
self.assertTrue(noteContent.index("添加的内容")>-1, "更新笔记失败")
56+
57+
if __name__ == '__main__':
58+
unittest.main(verbosity=0)
59+

‎timefriend/timefriend.py‎

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
import evernote.edam.type.ttypes as Types
2+
import evernote.edam.notestore.ttypes as Ttypes
3+
from evernote.api.client import EvernoteClient
4+
import html2text
5+
import time
6+
from datetime import datetime, date
7+
8+
class EverNote():
9+
def __init__(self, auth_token):
10+
self.auth_token = auth_token
11+
self.client = EvernoteClient(token=auth_token, sandbox=False,china=True)
12+
self.note_store = self.client.get_note_store()
13+
14+
self.template = '<?xml version="1.0" encoding="UTF-8"?>'
15+
self.template +='<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">'
16+
self.template +='<en-note>%s</en-note>'
17+
18+
def getTagGuid(self, name):
19+
if name is None:
20+
return None
21+
22+
for tag in self.note_store.listTags():
23+
if tag.name == name:
24+
return tag.guid
25+
26+
def getNotebookGuid(self, name):
27+
notebooks = self.note_store.listNotebooks()
28+
for notebook in notebooks:
29+
if notebook.name == name:
30+
return notebook.guid
31+
32+
def getNoteGuidByTagGuid(self, title, tagguid):
33+
f = Ttypes.NoteFilter()
34+
f.tagGuids = [tagguid]
35+
notes = self.note_store.findNotes(self.auth_token, f, 0, 999).notes
36+
for note in notes:
37+
if note.title == title:
38+
return note.guid
39+
40+
def getNoteContent(self, guid):
41+
note = self.note_store.getNote(self.auth_token, guid, True,False,False,False)
42+
return note.content
43+
44+
def getNoteText(self, guid):
45+
content = self.getNoteContent(guid)
46+
notetext = html2text.html2text(content)
47+
return notetext
48+
49+
def analysisNote(self, notetext):
50+
lines = notetext.split('\n\n')
51+
# 分类
52+
# 开始时间,结束时间 内容,分类,成本
53+
startTime = lines[0].split(" "*4)[0] # 当天记录的开始时间
54+
# return lines[0].split(" "*4)
55+
rows = []
56+
statistics = {
57+
"total": 0,
58+
"group": {}
59+
}
60+
begin = startTime # 每个记录的开始时间
61+
for l in lines[1:]:
62+
if not l.strip():
63+
continue
64+
row = {}
65+
parts = l.split(" "*4)
66+
row['begin'] = begin
67+
row['end'] = parts[0]
68+
row['description'] = parts[1]
69+
row['type'] = parts[2]
70+
row['cost'] = parts[3]
71+
rows.append(row)
72+
73+
group = statistics["group"].get(row['type'], 0)
74+
group += int(row['cost'])
75+
statistics["group"][row['type']] = group
76+
begin = row['end']
77+
if startTime > begin:
78+
statistics['total'] = difftime("2020年01月02日 " + begin + ":00", "2020年01月01日 " + startTime + ":00", "m")
79+
else:
80+
statistics['total'] = difftime("2020年01月01日 " + begin + ":00", "2020年01月01日 " + startTime + ":00", "m")
81+
print(startTime," ", begin)
82+
return statistics
83+
84+
def formatNote(self, text): # 将文字转换为印象笔记格式
85+
content = []
86+
for line in text.split("\n"):
87+
content.append(self.formatLine(line))
88+
return "".join(content)
89+
90+
def formatLine(self, line):
91+
tabstr = "&nbsp; &nbsp; "
92+
if line:
93+
return "<div>" + line.replace(" "*4, tabstr).replace("\t", tabstr) + "</div>"
94+
else:
95+
return "<div><br/></div>"
96+
97+
def createNote(self, title, content, tag=None, notebook="随手记"):
98+
# 得到 tags
99+
tagGuid = self.getTagGuid(tag) if tag else None
100+
101+
if tagGuid is None and tag is not None:
102+
tagGuid = self.createTag(tag)
103+
104+
# 得到 notebook
105+
notebookGuid = self.getNotebookGuid(notebook)
106+
# 格式化文本
107+
noteContent = self.formatNote(content)
108+
# 构造 note 对象
109+
note = Types.Note()
110+
note.title = title
111+
if tagGuid:
112+
note.tagGuids = [tagGuid]
113+
note.notebookGuid = notebookGuid
114+
note.content = self.template % noteContent
115+
116+
# 存入
117+
enote = self.note_store.createNote(self.auth_token, note)
118+
119+
return enote.guid
120+
121+
def createTag(self, name):
122+
tag = Types.Tag()
123+
tag.name = name
124+
tag = self.note_store.createTag(self.auth_token, tag)
125+
return tag.guid
126+
127+
def updateNote(self, guid, content, operation='a'):
128+
"""
129+
更新指定笔记的内容
130+
type: a 追加,r 替换
131+
"""
132+
note = self.note_store.getNote(self.auth_token, guid, True,False,False,False)
133+
noteContent = self.formatNote(content)
134+
135+
if operation == 'a':
136+
note.content = note.content.replace("</en-note>", "") + noteContent + "</en-note>"
137+
elif operation == 'r':
138+
note.content = self.template % noteContent
139+
else:
140+
raise "未知操作符 " + operation
141+
142+
self.note_store.updateNote(self.auth_token, note)
143+
return note.guid
144+
145+
def time2datetime(a_time, str_format="%Y-%m-%d %H:%M:%S"):
146+
if type(a_time) == datetime:
147+
return a_time
148+
if type(a_time) == date:
149+
return a_time
150+
if type(a_time) == time.struct_time:
151+
return datetime.utcfromtimestamp(time.mktime(a_time))
152+
if type(a_time) == float:
153+
return datetime.utcfromtimestamp(a_time)
154+
if type(a_time) == str:
155+
return datetime.strptime(a_time, str_format)
156+
pass
157+
158+
def difftime(timea, timeb, unit='S'):
159+
# 进行格式转换
160+
timea = time2datetime(timea)
161+
timeb = time2datetime(timeb)
162+
163+
timediff = timea - timeb
164+
# 转换为秒
165+
timecount = timediff.days*24*3600
166+
timecount += timediff.seconds
167+
timecount += timediff.microseconds/1000000
168+
169+
if unit == 'd': # 日
170+
return timecount / (24*3600)
171+
if unit == 'm': # 分
172+
return timecount / 60
173+
if unit == 'h': # 时
174+
return timecount / 3600
175+
if unit == 'S': # 秒
176+
return timecount
177+
if unit == 's': # 毫秒
178+
return timecount * 1000
179+
if unit == 'f': # 微妙
180+
return timecount * 1000000
181+
if unit == 'w': # 周
182+
return timecount / (24*3600*7)
183+
if unit == 'M': # 月
184+
return timecount / (24 * 3600 * 30)
185+
186+
if __name__ == '__main__':
187+
# 集成
188+
auth_token = "S=s1:U<...>5369" # 换成自己的 token
189+
client = EverNote(auth_token) # 创建代理实例
190+
191+
# 获取日志 text 内容
192+
tagGuid = client.getTagGuid("时间账")
193+
noteGuid = client.getNoteGuidByTagGuid("2020年03月18日", tagGuid)
194+
noteText = client.getNoteText(noteGuid)
195+
196+
ret = client.analysisNote(noteText) # 解析并分析
197+
198+
client.updateNote(noteGuid, ret.result) # 添加分析结果

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /