Created
December 8, 2013 19:00
-
-
Save mattiasostmar/7862242 to your computer and use it in GitHub Desktop.
A file based on: http://stackoverflow.com/questions/20456011/delete-whitespace-characters-in-quoted-columns-in-tab-separated-file/20457048?noredirect=1#20457048
This file contains 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
import re | |
import sys | |
_, infile, outfile = sys.argv | |
s_pat_row = r''' | |
"([^"]+)" # match column; this is group 1 | |
\s*\t\s* # match separating tab and any optional white space | |
([^\t]+) # match a string of non-tab chars; this is group 2 | |
\s*\t\s* # match separating tab and any optional white space | |
"((?:\\"|[^"])*)" # match string data that can include escaped quotes | |
''' | |
pat_row = re.compile(s_pat_row, re.MULTILINE|re.VERBOSE) | |
s_pat_clean = r'''[\x01-\x1f\x7f]''' | |
pat_clean = re.compile(s_pat_clean) | |
row_template = '"{}",{},"{}"\n' | |
with open(infile, "rt") as inf, open(outfile, "wt") as outf: | |
data = inf.read() | |
for m in re.finditer(pat_row, data): | |
row = m.groups() | |
cleaned = re.sub(pat_clean, ' ', row[2]) | |
words = cleaned.split() | |
cleaned = ' '.join(words) | |
outrow = row_template.format(row[0], row[1], cleaned) | |
outf.write(outrow) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment