如何从数字列表中替换单个数字(来自一组行)?

时间:2015-09-15 09:26:31

标签: python macros

我是编程/宏观等新手,我想这样做。 我应该使用word 2007或Python还是其他东西?我目前只有这两件事。

original message is this:
hello how are you ref=13515
ofdifaoididpodvjakjeoijknvkln
ikvnoivwoeij,vn,nviojv
nkavjoiewgkjvlkaior

此邮件的号码将被此列表中的号码替换

876191
11166524
1117225
1116953
798993
793519
1116737
1116691
1116364
1115635
909014
760195
689981
604787
1116217
1104482
869990
886290
1115893

并且该消息应该自动复制,因为该列表中有数字。

所以我的结果应该是

hello how are you ref=876191
ofdifaoididpodvjakjeoijknvkln
ikvnoivwoeij,vn,nviojv
nkavjoiewgkjvlkaior
hello how are you ref=11166524
ofdifaoididpodvjakjeoijknvkln
ikvnoivwoeij,vn,nviojv
nkavjoiewgkjvlkaior
hello how are you ref=1117225
ofdifaoididpodvjakjeoijknvkln
ikvnoivwoeij,vn,nviojv
nkavjoiewgkjvlkaior
and so on

请注意,列表中的数字是6或7或8位数字

谢谢

1 个答案:

答案 0 :(得分:1)

一个简单的Python脚本可以工作:

template = """hello how are you ref={}
ofdifaoididpodvjakjeoijknvkln
ikvnoivwoeij,vn,nviojv
nkavjoiewgkjvlkaior
"""

replace = [
    876191, 11166524, 1117225, 1116953, 798993,
    793519, 1116737, 1116691, 1116364, 1115635,
    909014, 760195, 689981, 604787, 1116217,
    1104482, 869990, 886290, 1115893]

print ''.join([template.format(r) for r in replace])

将显示:

hello how are you ref=876191
ofdifaoididpodvjakjeoijknvkln
ikvnoivwoeij,vn,nviojv
nkavjoiewgkjvlkaior
hello how are you ref=11166524
ofdifaoididpodvjakjeoijknvkln
ikvnoivwoeij,vn,nviojv
nkavjoiewgkjvlkaior
hello how are you ref=1117225
ofdifaoididpodvjakjeoijknvkln
ikvnoivwoeij,vn,nviojv
nkavjoiewgkjvlkaior
.
.
.

等等。

如果您想将输出直接写入文本文件,以下内容将起作用:

with open('output.txt', 'w') as f_output:
    f_output.write(''.join([template.format(r) for r in replace]))

如果您还想阅读文本文件中的数字,请使用以下内容:

with open('numbers.txt', 'r') as f_input, open('output.txt', 'w') as f_output:
    for number in f_input:
        f_output.write(template.format(number.strip()))