简体   繁体   English

将地址列表转换为逗号分隔列表

[英]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 ¶名称 1 ¶
Address1 ¶地址1 ¶
City1, State1, Zip1 ¶城市 1、州 1、邮编 1 ¶

Name2 ¶名称2 ¶
Address2 ¶地址2 ¶
City2, State2, Zip2 ¶ 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;但是,MS Office 的邮件合并功能需要地址列表是逗号分隔的列表; 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...?有谁知道如何通过 MS Office、Python 脚本等来做到这一点?

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.此脚本将以您提供的形式读取其标准输入上的文本,并将文本作为 CSV 写入其标准输出,每个输入段落一行,每个输入行一列。

Use it like so: python para2csv.py < inputfile.txt > outputfile.csv像这样使用它: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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