1. 程式人生 > >python開發-html富文字轉JSON

python開發-html富文字轉JSON

這只是一個開發思路,實現了字型固定格式轉存json,歡迎吐槽。

寫這段程式碼,是因為原生android textView 不支援html標籤樣式。(網上已找到textView支援html簡單標籤方法,請自行搜尋)

content = '''《寶貝兒》是由侯孝賢監製、<span style="font-weight: bold;">劉傑執導</span>、楊冪領銜主演,<span style="font-style: italic;">郭京飛</span>、李鴻其主演的一部文藝劇情片。今日(8月14日)<span style="text-decoration-line: line-through;">第43屆</span>多倫多國際電影節官方公佈影片《<span style="text-decoration-line: underline;">寶貝兒</span>》入圍本屆電影節“特別展映”單元。<a href="www.baidu.com" target="_Blank">影片講述的是一個因為嚴重先天缺陷而被父母拋棄的棄兒江萌(楊冪 飾)</a>,拯救另一個被父母宣判了“死刑”的缺陷嬰兒的故事。《寶貝兒》將在今秋9月舉行的多倫多國際電影節上全球首映,並將於10月19日全國公映。
'''
marks = ['<span style="font-weight: bold;">', '<span style="font-style: italic;">', '<span style="text-decoration-line: line-through;">', '<span style="text-decoration-line: underline;">', '<a href=', ]
count = content.count('</span>')
index = 0
contentList = []
print(content.find('<span style=', index), content.find('<a href=', index))
for i in range(count):
    index1 = 0;
    index2 = 0;
    index3 = 0;
    index4 = 0;
    style = '';
    link = ''
    spanIndex = content.find('<span style=', index)
    aIndex = content.find('<a href=', index)
    if aIndex == -1:
        index1 = spanIndex
        index2 = content.find('>', spanIndex) + 1
        index3 = content.find('</span>', index2)
        index4 = index3 + 7;
    elif spanIndex == -1:
        index1 = aIndex
        index2 = content.find('>', index1) + 1
        index3 = content.find('</a>', index2)
        index4 = index3 + 4
        link = content[content.find('href="', index1, index2) + 6:content.find('"', index1, index2)]
    elif spanIndex < aIndex:
        index1 = spanIndex
        index2 = content.find('>', spanIndex) + 1
        index3 = content.find('</span>', index2)
        index4 = index3 + 7;
    elif spanIndex > aIndex:
        index1 = aIndex
        index2 = content.find('>', index1) + 1
        index3 = content.find('</a>', index2)
        index4 = index3 + 4
        link = content[content.find('href="', index1, index2) + 6:content.find('"', index1, index2)]
    else:
        print('獲得索引出錯', spanIndex, aIndex)
    if content.find('bold', index1, index2) > -1:
        style = 'bold'
    elif content.find('italic', index1, index2):
        style = 'italic'
    elif content.find('line-through', index1, index2):
        style = 'line-through'
    elif content.find('underline', index1, index2):
        style = 'underline'
    else:
        print('判斷style出錯')
    print(index1, index2, index3, index4, link, style)
    contentList.append({'data':content[index:index1],'style':style,'link':link})
    contentList.append({'data':content[index2:index3],'style':style,'link':link})
    index = index4;
print(contentList)