简体   繁体   中英

Converting a list of addresses to a comma separated list

This is probably a pretty trivial problem, but here goes -- I have been given a plaintext list of addresses in this format:

Name1 ¶
Address1 ¶
City1, State1, Zip1 ¶

Name2 ¶
Address2 ¶
City2, State2, Zip2 ¶

... and so on. My job is to mail merge these into labels for envelopes. However, MS Office's mail merge function needs for the list of addresses to be a comma-separated list; it can't seem to distinguish between addresses in the format I was given. I can't figure out a way to convert this plaintext list to a comma-separated list. Would anyone know how to do this via MS Office, a Python script, etc...?

Thank you in advance!!

This script will read text on its standard input in the form you gave, and write text to its standard output as a CSV, with one row per input paragraph, one column per input line.

Use it like so: python para2csv.py < inputfile.txt > outputfile.csv

#!/usr/bin/python2.7

# Copy the input stream to the output stream, converting
# paragraphs into CSV rows.

import csv
import sys

def para(f):
    row = []
    for line in f:
        line = line.strip()
        if line:
            row.append(line)
        elif row:
            yield row
            row = []
    if row:
        yield row

writer = csv.writer(sys.stdout)
for row in para(sys.stdin):
    writer.writerow(row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM