Created
July 14, 2014 11:40
-
-
Save pingjiang/a71dd988f0d80c20cb1e to your computer and use it in GitHub Desktop.
You can generate markdown table from cvs like text file.
This file contains hidden or 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
#!/usr/bin/env python | |
#--*-- coding: UTF-8 --*-- | |
import sys | |
def generateNewParts(parts, isHeader = True): | |
if len(parts) == 3: | |
return parts | |
pos = parts[1].find('(') | |
if pos != -1: | |
rpos = parts[1].find(')', pos + len('(')) | |
if rpos != -1: | |
part1 = parts[1][0: pos] | |
part2 = parts[1][(pos + len('(')) : rpos] | |
part1Link = '[%s](http://www.baidu.com/s?wd=%s)'%(part1, part1) | |
return [parts[0], part1Link, part2] | |
return [parts[0], parts[1], parts[1]] | |
def mostValueable(parts, isHeader = True): | |
if len(parts) == 5: | |
return parts | |
if isHeader: | |
return parts[0:5] | |
part0 = '[%s](http://%s)'%(parts[0], parts[5]) | |
part4 = '[%s](http://www.baidu.com/s?wd=%s)'%(parts[4], parts[4]) | |
return [part0, parts[1], parts[2], parts[3], part4] | |
def cloudFilter(parts, isHeader = True): | |
if isHeader: | |
return parts | |
part0 = '[%s](http://%s)'%(parts[0], parts[2]) | |
part2 = '[%s](http://s.weibo.com/weibo/%s)'%(parts[0], parts[0]) | |
part3 = '[%s](http://%s/doc)'%('...', parts[2][0:-1] if parts[2].endswith('/') else parts[2]) | |
return [part0, parts[1], part2, part3] | |
def convertSimpleTextToMarkdown(lines, seperator = ' ', partsFilter = generateNewParts): | |
isHeader = True | |
for line in lines: | |
line = line.replace('\r', '').replace('\n', '') | |
if line.strip() == '': | |
continue | |
elif line.startswith('#'): | |
print(line) | |
else: | |
parts = line.split(seperator) | |
newparts = partsFilter(parts, isHeader) | |
print('|' + '|'.join(newparts) + '|') | |
if isHeader: | |
print('|'.ljust(2*len(newparts[0]), '-')*len(newparts) + '|') | |
isHeader = False | |
if __name__ == '__main__': | |
file_path = None | |
if len(sys.argv) > 1: | |
if sys.argv[1].startswith('-h'): | |
print('Usage: %s [filePath] [encoding]. \n\n Will use stdin if file path not specified, default encoding is UTF-8.\n'%(sys.argv[0])) | |
sys.exit(0) | |
file_path = sys.argv[1] | |
encoding = 'utf-8' | |
if len(sys.argv) > 2: | |
encoding = sys.argv[2] | |
lines = [] | |
if file_path != None: | |
with open(file_path) as f: | |
lines = f.readlines(); | |
else: | |
lines = sys.stdin.readlines() | |
# ' ', mostValueable | |
# ';', cloudFilter | |
convertSimpleTextToMarkdown(lines, ';', cloudFilter) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment